Greetings!
Here’s an absolutely ANNOYING side effect of using setTimeout() in JavaScript that I did not know, and absolutely nobody mentions - not even famous JavaScript book authors - that I found tucked away in an obscure post somewhere that I don’t remember.
The general syntax for a setTimeout() statement is like this:
var id = setTimeout(fn. delay);
Where “fn” is a function to be called after the delay ends and “delay” is the amount of time, in milliseconds, (1000ms = 1 second), that the timer should wait before running the function.
Nobody, and I mean NOBODY except for one obscure author mentions anything about the characteristics of the functional requirement.
Here’s the “gotcha”:
If the function you’re passing to the timer has ANY parameters, the timer returns immediately after pushing the function into the queue. Actually there’s a better, more technical explanation, but I forgot what it was.
For example:
var id = setTimeout(fn. delay); waits “delay” milliseconds and then executes “fn”.
However:
var id = setTimeout(fn(parameters). delay); returns immediately after pushing “fn(parameters)” on the execution queue which, essentially, causes it to execute immediately.
Why? Only the Gods of JavaScript know - and it’s a pain!
I noticed that when I run
var id = setTimeout(requestAnimationFrame(animation), 1000);
There was absolutely no delay whatsoever.
However if I run this:
function dothis() {
requestAnimationFrame(animation);
}
[more code]
setTimeout(dothis, 1000);
the execution of “requestAnimationFrame” is delayed by one-second intervals as it should be.
Annoying and (almost) totally un-documented.
Grrrrr!
P. S.
I don’t know if this is also the case for setInterval() or not.