What is the point of giving the time duation in setTimeout() function ? Altough the callback will have to wait for the call stack to be completely empty.
For example if i write this code.
setTimeout(()=>console.log("2 sec Timeout"),2000)
There is no gurantee that it will run exacatly after 2 seconds. If there are other codes which takes more time than 2 seconds , the setTimeout callback will have to wait for other code to run than it will run the timeout code. check the example below.
var c= ()=>{
setTimeout(()=>console.log("2 sec Timeout"),2000)
console.log("c");
}
var d= ()=>{
console.log("d");
for (let index = 0; index < 10000000000; index++) {
}
console.log("End of for loop");
}
var e= ()=>{
console.log("e");
for (let index = 0; index < 10000000000; index++) {
}
console.log("End of for loop");
}
c()
d()
e()
Here the settimeout code will have to wait for the completeion of d() than e() after that it will execute setTimeout Code.
Is there ay other way to execute the required code exactly after the required time interval.
What is the point of giving the time duation in setTimeout() function ?
To specify the approximate delay you want. Or to put it another way, to put a minimum figure on how soon the code should run (while accepting it may run later than that).
Is there ay other way to execute the required code exactly after the required time interval.
No, because JavaScript runs a single thread per realm (loosely, per global environment and such), and works using a job queue where once a job is started, it runs to completion and cannot be interrupted by another job. So since another job may be being run when the exact time you provide occurs, there is no way to schedule it exactly.
That said, it's not typically an issue except in code that either 1) Incorrectly assumes the timeout will occur after an exact amount of time, and/or 2) Incorrectly blocks the thread, as your example code is doing (though I assume that's just for the purposes of the example).
An example of issue #1: Suppose you have an animation (one that, for whatever reason, can't be done with CSS) that needs to run for two seconds and has (for instance) 20 states to animate through. Code falling prey to issue #1 would be written using twenty calls like setTimeout(/*...*/, 100)
on the assumption that each will take 100ms. That's incorrect for the reason you identified; the timing may be inaccurate. The correct way to write that code is to get the current time, use requestAnimationFrame
to request a callback just before the page is painted, and then use the current time in the callback to see how far along you are in real time and thus what stage of the animation to perform. If the thread is really busy, you might only manage a few updates instead of the full 20, but the animation will still end at about the right time, and each update will show the correct state for the time that update ran.