Exploring setTimeout and setInterval: JavaScript Timing Functions Explained

Exploring setTimeout and setInterval: JavaScript Timing Functions Explained

Hi 👋 fellow developers,

My name is Sandeep Singh, and I am an aspiring full-stack developer. If you are a beginner, you have probably tried to create a stopwatch or timer as one of your projects. In doing so, you may have come across the setTimeout and setInterval functions. In this article, I will explain these two amazing features of JavaScript. Although setTimeout and setInterval are not technically part of the JavaScript specification, most environments, such as browsers and Node.js, have internal schedulers that provide these methods. Let’s dive into understanding these two methods and the differences between them.

setTimeout()

Let's suppose you have a function sayHello and you want to execute it after a certain delay.

function sayHello() {
    console.log('Hello');
}

// Calling sayHello
sayHello(); // The function will execute immediately without any delay.

In such cases Javascript provides a method setTimeout to delay the execution of a function .

function sayHello() {
    console.log('Hello');
}

setTimeout(sayHello, 2000);

In the above code, we are using setTimeout to schedule the execution of sayHello function to run after a delay of 2000 milliseconds (2 seconds).

Understanding setTimeout syntax

setTimeout(function, delay, [arguments]);

function -the function you want to execute

delay-the delay time in milliseconds (1000ms=1 second )

arguments-Optional arguments to pass to the function when it executes.

Example with Arguments -

function sayHi(name){
console.log(`hello ${name} , how are you`);
}

setTimeout(sayHi , 2000 , "Sandeep");

From the above code we can observe That the function sayHi will execute automatically after a delay of 2 seconds (2000ms) and a argument “Sandeep” has been passed to it .

NOTE : don’t use sayHi() to call the function inside setTimeout . as this will immediately execute the function instead of delaying it.

Clearing timeout

There is also a method clearTimeout to clear the timer .

function sayHello() {
    console.log('Hello');
}

// Set a timeout to call sayHello after 5 seconds (5000 milliseconds)
let timerId = setTimeout(sayHello, 5000);

// Clear the timeout before it executes
clearTimeout(timerId);

setTimeout returns a timer id , which can be used in clearTimeout to stop the scheduled execution of setTimeout function. In the above code sayHello will not execute after 5 seconds as we are clearing it before it gets executed.

setInterval()

If you want to call a function repeatedly at a certain interval, you can use the setInterval method.

The setInterval method is used to execute a function repeatedly after a specified period.

its syntax is the same as setTimeout :

setInterval(function, delay, [arguments]);

Let's see an example:

function sayHi(name){
console.log(`hello ${name} , how are you`);
}

setInterval(sayHi , 2000 , "Sandeep");

By running the above code, you will observe that the sayHi function is called every 2 seconds.

Clearing interval

Similar to clearTimeout, there is a clearInterval method to stop the interval. You can use this method to stop the execution of the function at any point.

let num = 1;

function incrementNum() {
    console.log(num);
    num++;
    if (num > 10) {
        clearInterval(timerId); // Stop the execution of incrementNum if num exceeds 10.
    }
}

const timerId = setInterval(incrementNum, 2000);

In this article, we explored the setTimeout and setInterval methods in JavaScript . I encourage you to practice the above code in your code editor.

I hope you liked this article.

follow me for more similar articles on javascript and web development.