I've been fiddling around with setTimeout and setInterval, and I cannot get the code to execute the way I would like it to. My goal is to create a setInterval, which calls once every three seconds, and have it clear after ten seconds. However, when I run the code in firebug, the only thing I get is a number, which I assume is the id of setInterval because every time I execute the code, the number increases.
var intID = setInterval(function() {
console.log("I've been called");},3000);
setTimeout(clearInterval(intID), 10000);
This is because if you pass the parameters directly like this: setTimeout(greeting("Nathan", "Software developer"), 3000); Then JavaScript will immediately execute the function without waiting, because you're passing a function call and not a function reference as the first parameter.
Maximum delay value Browsers including Internet Explorer, Chrome, Safari, and Firefox store the delay as a 32-bit signed integer internally. This causes an integer overflow when using delays larger than 2,147,483,647 ms (about 24.8 days), resulting in the timeout being executed immediately.
The setTimeout() is executed only once. If you need repeated executions, use setInterval() instead. Use the clearTimeout() method to prevent the function from starting.
setTimeout and setInterval are the two timing events available in JavaScript. The setTimeout function executes when the given time is elapsed, whereas setInterval executes repeatedly for the given time interval. These timers are the most common cause of memory leaks.
This statement:
setTimeout(clearInterval(intID), 10000);
means, "call the function 'clearInterval' passing the value of variable 'intID', and then pass the return value of that and the number 10000
to the function 'setTimeout'."
In other words, you're calling the function "clearInterval" and then passing the returned value to setTimeout()
.
Instead, pass setTimeout()
a function:
setTimeout(function() { clearInterval(intID); }, 10000);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With