48

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>
Daerik
  • 3,572
  • 1
  • 17
  • 33
James Dorfman
  • 1,592
  • 5
  • 17
  • 32
  • 3
    [Learn how to **debug** JavaScript](http://www.creativebloq.com/javascript/javascript-debugging-beginners-3122820). You are trying to access a DOM element before it exists. Please see [Why does jQuery or a DOM method such as `getElementById` not find the element?](http://stackoverflow.com/q/14028959/218196). And please explain *what exactly* is not working. – Felix Kling Jan 02 '14 at 20:10
  • 2
    possible duplicate of [Why is the method executed immediately when I use setTimeout?](http://stackoverflow.com/questions/7137401/why-is-the-method-executed-immediately-when-i-use-settimeout) – Felix Kling Jan 02 '14 at 20:14

7 Answers7

121

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);
linstantnoodles
  • 3,997
  • 1
  • 16
  • 23
  • 2
    Yes, also as @j08691 notes--keeping the parens instantly triggers the function call. This was misleading me, as the function was being called without any errors or console warnings, so I wasn't doubting how I used the `setTimeout()`, but how I'd scoped it, etc. This was driving me crazy. Thanks to you both. – elrobis Jul 10 '14 at 20:38
  • 10
    What if you have to pass a variable in? – Jeff May 14 '15 at 18:04
  • 23
    @Jeff you would wrap it inside a closure. `setTimeout(function() { startTimer(parm1); }, startInterval);` See here for more info...http://stackoverflow.com/questions/7176292/how-to-pass-parameters-when-calling-a-function-without-the-parenthesis-javascri – abaldwin99 Aug 24 '15 at 14:48
25

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);
Matt Catellier
  • 629
  • 10
  • 18
12

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.

j08691
  • 190,436
  • 28
  • 232
  • 252
5

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

    setTimeout(setTimer, 3000, param1, param2);
user126587
  • 195
  • 2
  • 8
1

Use:

setTimeout(startTimer,startInterval); 

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

Roman Hocke
  • 3,793
  • 1
  • 18
  • 32
1

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.

Glenn Ferrie
  • 9,617
  • 3
  • 37
  • 67
1

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