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.

For instance, when they make AJAX requests to a server. It might take about half a second to get a response from the server. In such a scenario, the developer might get incorrect or no response if the code is executed is synchronously, or even worse, the application freezes until and unless a response is obtained i.e code is blocked until response obtained or execution timed out, which is a terrible user experience.

That is when asynchronous code came as a “Life Hack” for developers and also for end-user experience. Considering the use case of making AJAX/HTTP requests, asynchronous code allows the processing of that particular code snippet in the background without hampering execution of the block(s) of code following the asynchronous(shorthand: async) block of code.

Had a hard time following what I said about async code? In simple terms, the following steps are executed:

  • the async code gets processed in the background when an AJAX call to a server is made(Reminder: this is the most common, but not the only, use case of an asynchronous code execution).

This allows parallel(multi-threaded) execution of code when a certain piece of code depends on a delayed response. This also accounts for a better user experience

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’s take a simple example:

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

The expression under setTimeout() can be a function, as well as shown in the above example. In this example, when the javaScript file is executed, the arrow function sayHello is called inside the setTimeout() function which displays an alert box having the text Hello after 2 seconds(2000 milliseconds).

A point to note here is that setTimeout() doesn't stop the execution of that specific script after the timeout period. It merely schedules the specified javaScript code to be run at the specified time. After calling the setTimeout() function, the script continues normally, with the timer running in the background.

The above code snippet, however, can be written by defining a function as first argument, as follows:

setTimeout(()=>{ alert('Hello')}, 2000);

This is the most common way of incorporating a function inside a setTimeout() function.

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

The only difference is that, setTimeout() triggers the expression only once while setInterval() triggers the expression repeatedly even after the given interval of time. (unless it is instructed to do stop ).

To stop further calls, we should call clearInterval(timerId).

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

The above code snippet will log ‘Hello’ in the console after 2 seconds of executing the above script( setInterval() called for the first time). Then again after 2 seconds, it will log ‘Hello’ ( setInterval() called for the second time). Finally, it will log ‘Clearing the interval’ after 1 second(Total of 5 seconds have passed since the script started executing and clearInterval() called).

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