Cancel setTimeout Timer in JavaScript

What is setTimeout?

setTimeout() is a function that waits for some time and then runs your code.

Example:

    setTimeout(() => {
    console.log("Hello after 3 seconds!");
    }, 3000);

This will print "Hello after 3 seconds!" after waiting 3000 milliseconds (3 seconds).


How to Cancel setTimeout?

Sometimes you don’t want that code to run — maybe the user clicked a button or something changed. You can cancel it using clearTimeout().


Easy Step-by-Step:

  1. When you use setTimeout(), it gives you an ID.

  2. You save that ID in a variable.

  3. Use that ID with clearTimeout() to stop the timer.


Simple Example:

    // Step 1: Set the timer
    let timerId = setTimeout(() => {
    console.log("This message will NOT be shown.");
    }, 5000);

    // Step 2: Cancel the timer
    clearTimeout(timerId);

    console.log("Timer was cancelled!");

This will only print:

    Timer was cancelled!

It will not show "This message will NOT be shown." because we canceled the timer before it ran.


 Real-Life Example: Cancel Auto Save

Imagine your app saves something after 5 seconds — but if the user clicks "Save" earlier, we cancel the auto-save.

    <button id="saveBtn">Save Now</button>
    let autoSave = setTimeout(() => {
    console.log("Auto-saved!");
    }, 5000);

    document.getElementById("saveBtn").addEventListener("click", () => {
    clearTimeout(autoSave);
    console.log("Manual save done. Auto-save cancelled.");
    });

Summary (Super Simple):

FunctionWhat it does
setTimeout()Runs code after waiting some time
clearTimeout()Stops that code from running