
As we discussed earlier setTimeout() starts it's timer and goes to task queue and waits until the call stack is empty. This is all a part of the event loop working.
setTimeout()
Example code:
functionsayHi(){alert('Hello');}setTimeout(sayHi,10000);
HeresayHi
function is executed after a delay of 10000 ms.
setTimeout()
doesn't necessarily execute the callback function precisely after the time inserted.
As it waits for the call stack to be empty, it might be the case that the timer has already expired while waiting, which means it will execute after a while and not the time mentioned.
Hence,
functionsayHi(){alert('Hello');}setTimeout(sayHi,0);...
Even here, it will wait till the whole program is executed and call stack isempty.
By remaining in task queue, it makes sure to avoid thread blocking. So:
- It waitsatleast the time mentioned to execute the callback.
- It does not block the main thread.
setInterval()
It keeps on executing the callback function after given interval until stopped.
lettimerId=setInterval(()=>console.log('attention'),2000);setTimeout(()=>{clearInterval(timerId);console.log('stop');},5000);
Here, the 'attention' is printed after every 2 seconds and it's cleared usingclearInterval()
below after 5 seconds, that is when stop is printed.
Learn more about concurrency in javascript and how can setTimeout(0) is used.
🌟setTimeout() by Akshay Saini
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse