javascript setTimeout() not working
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);
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);
Two things.
Remove the parenthesis in
setTimeout(startTimer(),startInterval);
. Keeping the parentheses invokes the function immediately.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.