嗨我正在尝试在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>
Run Code Online (Sandbox Code Playgroud)
lin*_*les 104
这一行:
setTimeout(startTimer(), startInterval);
Run Code Online (Sandbox Code Playgroud)
你在调用startTimer()
.相反,您需要将其作为要调用的函数传递,如下所示:
setTimeout(startTimer, startInterval);
Run Code Online (Sandbox Code Playgroud)
Mat*_*ier 19
如果您需要将参数传递给要在超时后执行的函数,则可以将"named"函数包装在匿名函数中.
即工作
setTimeout(function(){ startTimer(p1, p2); }, 1000);
Run Code Online (Sandbox Code Playgroud)
即不起作用
setTimeout( startTimer(p1, p2), 1000);
Run Code Online (Sandbox Code Playgroud)
j08*_*691 10
两件事情.
删除括号setTimeout(startTimer(),startInterval);
.保持括号立即调用该函数.
您的startTimer函数将使用您的内容覆盖页面内容document.write
(没有上述修复),并在此过程中清除脚本和HTML.
归档时间: |
|
查看次数: |
83359 次 |
最近记录: |