RAHULISM

RAHULISM

What is Scheduling in JavaScript?

What is Scheduling in JavaScript?

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

Generally, these two things disturb and irritate a lot when learning JS. In this post, we'll learn how to use them as a beginner.

Sometimes we may decide to execute a function after a certain time delay. That's called "scheduling a call".

  • setTimeout(): This method allows to execute a function only once after the specified time delay.
  • setInterval(): This method is used to execute a function repeatedly, starting after the time interval and then continues with equal intervals.

setTimeout()

This executes the function passed to it only once after the delay time has elapsed. Eg:

function greet() {
    console.log('Hello there!'); 
}
setTimeout(greet,1000); 
// var timerId=setTimeout(...); 
// clearTimeout(timerId);

Here, we execute the function "greet" with setTimeout(). It will console the output after a delay of 100ms. The setTimeout function returns a timerId which can be used to clear the timeout using the clearTimeout() method using the syntax mentioned in comments.


setInterval()

This executed the function passed to it after the time delay and then keeps on continuing with an equal interval of time delay. Eg:

function greet() {
    console.log('Hello there!'); 
}
setTimeout(greet,1000); 
// var timerId=setInterval(...); 
// clearInterval(timerId);

Here, we execute the function "greet" with setInterval. It will console after a delay of 1000ms and will continue to do the same after every 1000ms. This also returns a timeId similar to setTimeout() and can be cleared using setInterval() in the same manner.


😎Thank You For Reading | Happy Coding⚡

Interested in reading more such articles from Rahul?

Support the author by donating an amount of your choice.

Recent sponsors
 
Share this