Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for setTimeout() & setInterval() in javascript
Aishanii
Aishanii

Posted on

     

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:

functionsayHi(){alert('Hello');}setTimeout(sayHi,10000);
Enter fullscreen modeExit fullscreen mode

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);...
Enter fullscreen modeExit fullscreen mode

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);
Enter fullscreen modeExit fullscreen mode

Image description

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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I journal tech learnings and may give my 2 cents💁‍♀️ | Follow my System design journey!
  • Location
    India
  • Joined

More fromAishanii

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp