[javascript] javascript setTimeout() not working

Hi I'm trying to use the function setTimeout() in javascript except it's not working. Thanks in advance to anyone who can help.

<!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>

This question is related to javascript

The answer is


Please change your code as follows:

<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>

See if that helps. Basically, the difference is references the 'startTimer' function instead of executing it.


Two things.

  1. Remove the parenthesis in setTimeout(startTimer(),startInterval);. Keeping the parentheses invokes the function immediately.

  2. Your startTimer function will overwrite the page content with your use of document.write (without the above fix), and wipes out the script and HTML in the process.


Use:

setTimeout(startTimer,startInterval); 

You're calling startTimer() and feed it's result (which is undefined) as an argument to setTimeout().


If you want to pass a parameter to the delayed function:

    setTimeout(setTimer, 3000, param1, param2);

If your in a situation where you need to pass parameters to the function you want to execute after timeout, you can wrap the "named" function in an anonymous function.

i.e. works

setTimeout(function(){ startTimer(p1, p2); }, 1000);

i.e. won't work because it will call the function right away

setTimeout( startTimer(p1, p2), 1000);

To make little more easy to understand use like below, which i prefer the most. Also it permits to call multiple function at once. Obviously

setTimeout(function(){
      startTimer();
      function2();
      function3();
}, startInterval);