DEV Community

Cover image for Asynchronous JS: Finally discover how to use SetTimeout and SetInterval
Lorenzo
Lorenzo

Posted on • Updated on

Asynchronous JS: Finally discover how to use SetTimeout and SetInterval

Hello World! The fifth episode of the series - A CSS/JS trick in 5 minutes - Last Article was about a JS trick (On scroll event)
I want to show you another Javascript trick: How to work with SetTimeout and SetInterval.


SetTimeout will wait foo seconds and then execute the action. SetInterval will execute this same action every foo seconds.
Both can be inline or multiline, I recommend using multiline 99% of the time. It's important to notice that they work in milliseconds.

SetTimeout:

setTimeout(function(){
    alert("Hello World!"); 
}, 2000); // 2 seconds 

setTimeout(function(){ alert("The fifth episode of the series"); }, 3000);
Enter fullscreen mode Exit fullscreen mode

SetInterval:

setInterval(function() {
  alert("I want to show you another Javascript trick:");
}, 1000); 

setInterval(function() {alert("How to work with SetTimeout and SetInterval");}, 1000); 
Enter fullscreen mode Exit fullscreen mode
  • If you want to remove the first delay you have to add code a first time out of the function. I recommend you save this code in a separate function you can call whenever you need.

I also recommend you to don't use SetInterval but an advanced SetTimeout. This stack overflow explains why.

function foo() {
   alert("Remember the like ♡") 
   setTimeout(foo, 1000);
}

// start the cycle
foo();
Enter fullscreen mode Exit fullscreen mode

If you want to understand more about how SetTimeout and SetTimeout works.

Javascript is singled-threaded but the browser is not. The browser has at least three threads: Javascript engine thread, UI thread, and timing thread, where the timing of setTimeout and setInterval are done by the timing thread.
When calling setTimeout or setInterval, a timer thread in the browser starts counting down and when time up puts the callback function in javascript thread's execution stack. The callback function is not executed before other functions above it in the stack finishes. So if there are other time-consuming functions being executed when time up, the callback of setTimeout will not finish in time. Stack Overflow


Hope this helped and thanks for reading!

Please smash that like button to make me understand that you want the series to continue


Subscribe to our newsletter!

A loooong, and fun, weekly recap for you
Free PDF version of my articles
Highly customizable inbox
That's --> free <-- and you help me!

Top comments (0)