Cancellation of setTimeout()

JavaScript provides a corresponding function called clearTimeout() to cancel a scheduled timeout before it gets executed.

Example: In this example, we have shown the cancellation of settimeout..

Javascript
function delayedFunction() {
    console.log("This won't be executed due to clearTimeout");
}

let timeoutId = setTimeout(delayedFunction, 2000);

// Cancel the setTimeout before it executes
clearTimeout(timeoutId);

console.log("Timeout canceled");

What is the purpose of setTimeout() function in JavaScript ?

In JavaScript, the setTimeout() function is vey good for adding delays or scheduling the execution of a specific function after a certain period. It’s a key feature of both browser environments and Node.js, enabling asynchronous behavior in code execution. Whether you’re building a web application or a server-side script, setTimeout() offers flexibility in managing timing-related tasks without blocking the rest of your program’s flow.

Syntax:

setTimeout(function, milliseconds, arg1, arg2, ...);

Parameters:

  • function: After the specified time period, this is the function that is executed.
  • milliseconds: The delay time is expressed in milliseconds.
  • arg1arg2: If needed, these are the optional parameters.

Similar Reads

1. Cancellation of setTimeout()

JavaScript provides a corresponding function called clearTimeout() to cancel a scheduled timeout before it gets executed....

2. Purpose of setTimeout()

In JavaScript, the setTimeout() function is utilized to introduce a delay or to execute a particular function after a specified amount of time has passed. It is part of the Web APIs provided by browsers and Node.js, allowing asynchronous execution of code....