set Timeout() and clearTimeout() in JavaScript

set Timeout() and clearTimeout() in JavaScript

The setTimeout() method executes a block of code after the specified time. The method executes the code only once.

syntax- setTimeout(function, milliseconds);

The setTimeout()method returns an intervalID , which is a positive integer

function greet() {
    console.log('Hello world');
}

setTimeout(greet, 3000);
console.log('This message is shown first');

//output
This message is shown first
Hello world

JavaScript clearTimeout()

As you have seen in the above example, the program executes a block of code after the specified time interval. If you want to stop this function call, you can use the clearTimeout() method.

syntax-: clearTimeout(intervalID);

// program to stop the setTimeout() method
let count = 0;

// function creation
function increaseCount(){

    // increasing the count by 1
    count += 1;
    console.log(count)
}
let timeoutId = setTimeout(increaseCount, 3000);

// clearTimeout
clearTimeout(id); 
console.log('setTimeout is stopped.');

Arguments

You can also pass additional arguments to the setTimeout() method. The syntax is:

setTimeout(function, milliseconds, parameter1, ....paramenterN);
ex -// program to display a name
function greet(name, lastName) {
    console.log('Hello' + ' ' + name + ' ' + lastName);
}

// passing argument to setTimeout
setTimeout(greet, 1000, 'John', 'Doe');