An Interest In:
Web News this Week
- April 2, 2024
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
setTimeout() & setInterval() in javascript
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:
function sayHi() { alert('Hello');}setTimeout(sayHi, 10000);
Here sayHi
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,
function sayHi() { alert('Hello');}setTimeout(sayHi, 0);...
Even here, it will wait till the whole program is executed and call stack is empty.
By remaining in task queue, it makes sure to avoid thread blocking. So:
- It waits atleast 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.
let timerId = 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 using clearInterval()
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
Original Link: https://dev.to/aishanipach/settimeout-setinterval-in-javascript-83b
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To