Learning Objectives:
- setTimeout
- clearTimeout
- How to conditionally cancel action?
Window object has setTimeout method to perform some actions after a time interval in millisecond and clearTimeout to cancel the action.
To conditionally cancel an action that has been scheduled using setTimeout, you can store the timeout ID returned by setTimeout() and use clearTimeout() to cancel it based on certain conditions.
Here’s a basic flow for how this works:
Store the timeout ID: When you call setTimeout(), it returns a unique identifier (timeout ID).
Use clearTimeout() conditionally:
Based on some condition, you can call clearTimeout() with the stored timeout ID to cancel the action before it runs.
Example:
let timeoutId; // Variable to store the timeout ID
// Function to schedule an action
function scheduleAction() {
timeoutId = setTimeout(function() {
console.log("Action executed after 3 seconds!");
}, 3000); // Executes after 3000 milliseconds (3 seconds)
}
// Function to conditionally cancel the scheduled action
function cancelAction(condition) {
if (condition) {
clearTimeout(timeoutId); // Cancels the scheduled action
console.log("Action canceled!");
}
}
// Schedule the action
scheduleAction();
// Condition to cancel the action after 1 second (just as an example)
setTimeout(function() {
cancelAction(true); // Cancel the action based on condition
}, 1000);
How it works:
- scheduleAction(): This function sets up a setTimeout that logs a message after 3 seconds.
- cancelAction(condition): This function checks the condition, and if the condition is true, it calls clearTimeout(timeoutId) to cancel the scheduled action before it gets executed.
In this example, we schedule the action and then cancel it after 1 second based on a condition.
Output:
Action canceled! // Action is canceled before the 3-second timeout completes.
If you change the condition to false and wait longer (or remove the call to cancelAction), the action would execute as scheduled after 3 seconds.
Key Points:
- Store the timeout ID: The value returned by setTimeout() is crucial for calling clearTimeout() later.
- Conditional check: You can call clearTimeout() based on any condition you need (such as checking user input, state changes, etc.). This allows you to control when and whether the action gets executed, offering flexibility in your code.
No comments:
Post a Comment