'Why is JavaScript's Set Timeout not working? [closed]

I'm trying to use setTimeout, But it doesn't work. Any help is appreciated.

Anyone know how to fix this?

var button = document.getElementById("reactionTester");
var start  = document.getElementById("start");

function init() {
    var startInterval/*in milliseconds*/ = 1000;
    setTimeout(startTimer(), startInterval);
}

function startTimer() {
    document.write("hey");
}


Solution 1:[1]

This line:

setTimeout(startTimer(), startInterval); 

You're invoking startTimer(). Instead, you need to pass it in as a function to be invoked, like so:

setTimeout(startTimer, startInterval);

Solution 2:[2]

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

Solution 3:[3]

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.

Solution 4:[4]

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

    setTimeout(setTimer, 3000, param1, param2);

Solution 5:[5]

Use:

setTimeout(startTimer,startInterval); 

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

Solution 6:[6]

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.

Solution 7:[7]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 j08691
Solution 4 user126587
Solution 5 Roman Hocke
Solution 6 Glenn Ferrie
Solution 7 Muthukumar Anbalagan