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.