最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - clearTimeout() inside setTimeout() method not working in JS - Stack Overflow

programmeradmin4浏览0评论

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

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

Share Improve this question edited Mar 15, 2013 at 17:27 Felix Kling 817k180 gold badges1.1k silver badges1.2k bronze badges asked Mar 15, 2013 at 17:24 Kathirvel ShanmugasundaramKathirvel Shanmugasundaram 1531 gold badge1 silver badge11 bronze badges 2
  • 8 It does "work", but your logic is incorrect. After you called clearTimeout you are calling setTimeout again. Instead of calling clearTimeout you should just exit the function. – Felix Kling Commented Mar 15, 2013 at 17:26
  • See here as @Felix pointed jsfiddle/SEGtY/7 – Rodrigo Siqueira Commented Mar 15, 2013 at 17:28
Add a ment  | 

2 Answers 2

Reset to default 9

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);
}

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) }

发布评论

评论列表(0)

  1. 暂无评论