Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clearTimeout() inside setTimeout() method not working in JS

clearTimeout() inside setTimeout() method not working in JavaScript

var c = 0;
var t;

function timedCount() {
    document.getElementById('txt').value = c;
    c = c + 1;
    if (c == 5) {
        clearTimeout(t);
    }
    t = setTimeout(function () {
        timedCount()
    }, 1000);
}

jsFiddle

like image 579
Kathirvel Shanmugasundaram Avatar asked Mar 15 '13 17:03

Kathirvel Shanmugasundaram


People also ask

Why setTimeout is not working in JS?

This is due to when a function is executed as a parameter to setTimeout , the execution context is different to the execution context of the function! Now this will print out undefined because the this keyword is executed in the context of the setTimeout function and is therefore not defined.

How do you call clearTimeout?

You need to pass the amount of time to wait for in milliseconds , which means to wait for one second, you need to pass one thousand milliseconds . To cancel a setTimeout() method from running, you need to use the clearTimeout() method, passing the ID value returned when you call the setTimeout() method.

What is use of clearTimeout in JavaScript?

The global clearTimeout() method cancels a timeout previously established by calling setTimeout() . If the parameter provided does not identify a previously established action, this method does nothing.

How do I stop nested setTimeout?

setTimeout(() => clearTimeout(id), y_mili); it'll clear the timeout with the id at that time, as you evaluate id when the timeout is done, and not when it get's started.


2 Answers

You need to prevent the rest of the code of executing, actually you are re-declaring t after clearing the setTimeout. Fiddle

var c = 0;
var t;

function timedCount() {
    document.getElementById('txt').value = c;
    c = c + 1;
    if (c == 5) {
        clearTimeout(t);
        return false;
    }
    t = setTimeout(timedCount, 1000);
}

Or just use the else statement:

if (c == 5) {
  clearTimeout(t);
  // do something else
}else{
  t = setTimeout(timedCount, 1000);
}
like image 129
Pierre Avatar answered Sep 21 '22 23:09

Pierre


There will never be a timeout to clear when you call clearTimeout as the last one will have already fired and the next one won't have been set yet.

You want to change your logic so that if (c !== 5) { setTimeout(etc etc) }

like image 45
Quentin Avatar answered Sep 18 '22 23:09

Quentin