您好我正在尝试在javascript中使用函数setTimeout(),除非它不起作用。提前感谢任何可以提供帮助的人。
<!DOCTPYE html>
<html>
<head>
<script>
var button = document.getElementById("reactionTester");
var start = document.getElementById("start");
function init() {
var startInterval/*in milliseconds*/ = Math.floor(Math.random() * 30) * 1000;
setTimeout(startTimer(), startInterval);
}
function startTimer() {
document.write("hey");
}
</script>
</head>
<body>
<form id="form">
<input type="button id=" reactionTester" onclick="stopTimer()">
<input type="button" value="start" id="start" onclick="init()">
</form>
</body>
</html>
答案 0 :(得分:99)
这一行:
setTimeout(startTimer(), startInterval);
您正在调用startTimer()
。相反,您需要将其作为函数传递给,如下所示:
setTimeout(startTimer, startInterval);
答案 1 :(得分:17)
如果你需要将参数传递给你想要在超时后执行的函数,你可以包装&#34;命名&#34;在匿名函数中起作用。
即。作品
setTimeout(function(){ startTimer(p1, p2); }, 1000);
即。不会工作,因为它会立即调用该功能
setTimeout( startTimer(p1, p2), 1000);
答案 2 :(得分:10)
两件事。
删除setTimeout(startTimer(),startInterval);
中的括号。保持括号立即调用该函数。
您的startTimer函数将使用document.write
覆盖页面内容(没有上述修复),并在此过程中清除脚本和HTML。
答案 3 :(得分:3)
如果要将参数传递给延迟函数:
setTimeout(setTimer, 3000, param1, param2);
答案 4 :(得分:1)
请按以下方式更改您的代码:
<script>
var button = document.getElementById("reactionTester");
var start = document.getElementById("start");
function init() {
var startInterval/*in milliseconds*/ = Math.floor(Math.random()*30)*1000;
setTimeout(startTimer,startInterval);
}
function startTimer(){
document.write("hey");
}
</script>
看看是否有帮助。基本上,差异是引用'startTimer'函数而不是执行它。
答案 5 :(得分:1)
更容易理解使用,如下所示,我最喜欢。它还允许一次调用多个功能。显然
setTimeout(function(){
startTimer();
function2();
function3();
}, startInterval);
答案 6 :(得分:0)
使用:
setTimeout(startTimer,startInterval);
您正在调用startTimer()并将其结果(未定义)作为setTimeout()的参数提供。