JavaScript setTimeout() method example

Introduction :

setTimeout() method is used to execute a piece of code after a certain delay. In this post, I will show you how to use setTimeOut with examples.

setTimeout :

setTimeout takes two parameters : one function and time in milliseconds. It is defined as below :

setTimeout(fun, time)

Here, fun is the first parameter function and time is the time in milliseconds.

It executes the function after the time interval we are passing.

Example of setTimeout :

Let’s consider the below example :

setTimeout(() => {
    console.log("Hello !");
},2000)

This program will execute the console.log statement after 2 seconds or 2000 milliseconds of time. We can also write this piece of code as like below :

function printHello() {
    console.log("Hello !");
}

setTimeout(printHello, 2000);

Return value and clearTimeout :

It returns one positive integer, called timeoutID. This is an unique value to identify the timer created. This value can be passed to clearTimeout method to cancel the TimeOut.

function printHello() {
    console.log("Hello !");
}

let timeoutId = setTimeout(printHello, 2000);

clearTimeout(timeoutId);

This program will not print the message because we have cancelled the setTimeout using clearTimeout.

Passing arguments to the function :

If the function takes arguments, we can pass them as the arguments after the delay time.

For example :

function printHello(name, msg) {
    console.log(`Hello ${name}! ${msg}`);
}

setTimeout(printHello, 2000, 'Alex', 'Good Morning.');

Here we are passing ‘Alex’ and ‘Good Morning.’ as the first and second arguments to printHello function. It will print :

Hello Alex! Good Morning.

Similar tutorials :