Scheduling: setTimeout() and setInterval() in JS

Scheduling: setTimeout() and setInterval() in JS

Introduction

A block of JavaScript code is generally executed synchronously. There will be situations when you will want to delay the execution. Or, you may want to repeat the execution in specific intervals.

The setTimeout() and setInterval() are two methods you can use to schedule tasks in JavaScript.These let you run a piece of JavaScript code at some point in the future. That’s known as “scheduling a call”.

There is one interesting thing about these two methods to schedule tasks. None of them is a part of JavaScript language specification. These methods are actually part of HTML Living Standard specification , defined as "timers". Fortunately, they are supported in all browsers, even in Node.js. So, we can use them safely. Let's take a look at them.

minions-strong.gif

Scheduling

Any activity that's planned at a future interval is mostly brought up as scheduling. Both the functions allow you to execute a chunk of JavaScript code/function at a specific point within the future.

setTimeout()
setInterval()

These allow you to run a chunk of JavaScript code at some point within the future. That’s referred to as “scheduling a call”.

setTimeout()

The setTimeout() function is commonly used if you wish to run your function a specified number of milliseconds from when the setTimeout()method was called. It do 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. The general syntax of the method is:

// setTimeout general syntax
setTimeout ( expression, timeout );
setTimeout(callbackFunction, delay, arg1, arg2, ...arg(n))


// setTimeout method example 
// setTimeout method that waits for 2 seconds and then prints a message
setTimeout(()=> {
  console.log('Call Timeout')
}, 2000) // Delay is specified in milliseconds

// Output (after 2000 milliseconds):
Call Timeout.

// setTimeout method example with additional arguments
setTimeout((brand, msg) => {
  console.log(`${brand} ${msg}.`)
}, 2000, 'Welcome to', 'BMW')

// Output (after 2 seconds):
'Welcome to BMW.'

setInterval()

The setInterval() function, as the name suggests is commonly used to set a delay for functions that are executed again and again like animations. The setInterval() function is very closely related to setTimeout() - they even have same syntax:

setInterval ( expression, interval );
setInterval ( expression, interval, param1, param2, ... );

// Example 1
//This function will be invoked repeatedly at a interval of 2 seconds
setInterval(()=> console.log('Welcome'), 2000);

// Output after 2 seconds
This brand is BMW

// Example 2
let timerId = setInterval(() => console.log('Welcome'), 2000);
setTimeout(() => { clearInterval(timerId); console.log('stop'); }, 10000);

// Here, the 'Welcome' is printed after every 2 seconds 
// It is cleared using clearInterval() below after 10 seconds
// That is when stop is printed.

Difference

setTimeout() triggers the expression only once while setInterval() keeps triggering expression regularly after the given interval of time (unless you tell it to stop) and to stop further calls, we should call clearInterval(timerId).

Conclusion

When you need to invoke a function once after a specified duration use setTimeout() function. But, if you need to invoke a function repeatedly at a specified interval of time, then you should use setInterval() function.

Thanks for reading and I hope you found the article interesting.

If you found the article helpful, please like and share it. Follow me on Hashnode to get regular updates when I publish a new article. You can also connect with me on Twitter and check out my Github.

Also, I would love to hear any feedback from you.