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ā”
Top comments (3)
Really? I'd flip it around and claim that until you understand JavaScript's event loop, task and microtask queues you're going to have a hard time understanding its bread-and-butter asynchronous behaviour given that it has to accomplish work concurrently on a single thread.
setTimeout
andsetInterval
run on the Task queue, Promises (and therefore async/await) run on the microtask queue.Resources:
Helpful man. Thanks.
The second code method should be corrected to setInterval. Thanks