javascript setTimeout()不起作用

Jam*_*man 41 javascript

嗨我正在尝试在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)

  • @Jeff你会将它包装在一个封闭内.`setTimeout(function(){startTimer(parm1);},startInterval);`有关详细信息,请参阅此处... http://stackoverflow.com/questions/7176292/how-to-pass-parameters-when-calling-一个功能 - 不 - 的 - 括号 - javascri (19认同)
  • 如果必须传入变量怎么办? (10认同)
  • 是的,同样是@ j08691注意事项 - 保持parens立即触发函数调用.这误导了我,因为函数被调用时没有任何错误或控制台警告,所以我并不怀疑我是如何使用`setTimeout()`,而是我如何使用它等等.这让我发疯了.谢谢你们俩. (2认同)

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

两件事情.

  1. 删除括号setTimeout(startTimer(),startInterval);.保持括号立即调用该函数.

  2. 您的startTimer函数将使用您的内容覆盖页面内容document.write(没有上述修复),并在此过程中清除脚本和HTML.


use*_*587 5

如果要将参数传递给延迟函数:

    setTimeout(setTimer, 3000, param1, param2);
Run Code Online (Sandbox Code Playgroud)