setInterval() vs setTimeout(): synchronous vs asynchronous code execution in JavaScript

Scheduling techniques in JavaScript to understand execution of asynchronous code — synchronous vs asynchronous code

Synchronous and Asynchronous code

At it’s core, JavaScript is single threaded and code execution in JavaScript is synchronous, i.e: sequential execution of code. A latter block of code is executed only when a former block of code finishes execution. However, this might lead to certain problems for developers, especially when they’re expecting a result from a certain block of code which might take some time.

  • the blocks of code following the async code snippet are executed while the request to the server made by the async code snippet is being processed in the background
  • as soon as the async code snippet gets a response from the server it made the AJAX call to, the result of the computations of the async code gets updated in the original code, usually via a Promise or a callback function.

setTimeout() vs setInterval

In some cases we might chose to delay execution of a certain piece of code by a certain amount of milliseconds, thus responding to that code would be an asynchronous task. JavaScript has 2 native functions which allows us to delay our code execution by a certain amount of time.

setTimeout()

The setTimeout() function executes a piece of code after a certain amount of time(in milliseconds). The syntax is:

setTimeout(expression, timeout_in_milliseconds)
let sayHello = () => {
alert('Hello');
}
setTimeout(sayHello, 2000);
setTimeout(()=>{ alert('Hello')}, 2000);

setInterval()

The setInterval() function, as the name suggests, is commonly used to set a delay for functions that are repeatedly executed. The setInterval() function is very closely related to setTimeout() , they even share a similar syntax:

setInterval(expression, interval);
// Hello is logged into the console repeatedly after every 2 seconds
let timerInstance= setInterval(() => console.log('Hello'), 2000);
// Clear intervals after 5seconds with the timer id
setTimeout(() => { clearInterval(timerInstance); console.log('Clearing the interval'); }, 5000);

When to use what!!

When should one use setInterval() ?

If regular, precise timing is needed or something needs to be done repeatedly after certain time intervals, then setInterval() is your best choice, since using setInterval() there's virtually no delay between one triggering of the expression and the next.

When should one use setTimeout() ?

With setTimeout(), there's a comparatively long delay while the expression is evaluated, the function called, and the new setTimeout() being set up. So, if such a delay is acceptable in an application, setTimeout() is the way to go.

Backend Developer at Tricog Health, Bangalore. https://github.com/Sayan3sarkar