Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
July 18, 2022 08:01 am GMT

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);

Image description

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

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To