Why is JavaScript's Set Timeout not working?
JavascriptJavascript Problem Overview
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");
}
Javascript Solutions
Solution 1 - Javascript
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 - Javascript
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 - Javascript
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.
Solution 4 - Javascript
If you want to pass a parameter to the delayed function:
setTimeout(setTimer, 3000, param1, param2);
Solution 5 - Javascript
Use:
setTimeout(startTimer,startInterval);
You're calling startTimer() and feed it's result (which is undefined) as an argument to setTimeout().
Solution 6 - Javascript
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 - Javascript
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);