我在哪里放置clearTimeOut?

时间:2015-01-21 10:06:25

标签: javascript jquery

尝试以下

var timeoutId = setTimeout(function() {
    if ("comboFilters[Agencies]" in partDic) {
        var ag = partDic["comboFilters[Agencies]"].substring(1);
        $('.Agency .dropdown-toggle').html(ag).append(' <span class="caret"></span>');
    }

    if ("comboFilters[Clients]" in partDic) {
        var cl = partDic["comboFilters[Clients]"].substring(1);
        $('.Client .dropdown-toggle').html(cl).append(' <span class="caret"></span>');
    }

    if ("comboFilters[Years]" in partDic) {
        var yr = partDic["comboFilters[Years]"].substring(1).slice(1);
        $('.Year .dropdown-toggle').html(yr).append(' <span class="caret"></span>');
    }
    clearTimeout(timeoutId);
}, 1000);

1 个答案:

答案 0 :(得分:1)

只有在重复计时器的范围内才有意义。对于该用途setInterval和匹配的clearInterval

var timeoutId = setInterval(function() {
    if ("comboFilters[Agencies]" in partDic) {
        var ag = partDic["comboFilters[Agencies]"].substring(1);
        $('.Agency .dropdown-toggle').html(ag).append(' <span class="caret"></span>');
    }

    if ("comboFilters[Clients]" in partDic) {
        var cl = partDic["comboFilters[Clients]"].substring(1);
        $('.Client .dropdown-toggle').html(cl).append(' <span class="caret"></span>');
    }

    if ("comboFilters[Years]" in partDic) {
        var yr = partDic["comboFilters[Years]"].substring(1).slice(1);
        $('.Year .dropdown-toggle').html(yr).append(' <span class="caret"></span>');
    }
    clearInterval(timeoutId);
}, 1000);

显然,你只会在特定情况下拨打clearInterval(否则一个setTimeout会做同样的工作)。

e.g。

    if ($hit + fan == "hit"){
        clearInterval(timeoutId);   // stop further calls occurring
    }

只是澄清一下。如果您只想运行一次,请致电setTimeout,不要担心返回值或clearTimeout

setInterval(function() {
    if ("comboFilters[Agencies]" in partDic) {
        var ag = partDic["comboFilters[Agencies]"].substring(1);
        $('.Agency .dropdown-toggle').html(ag).append(' <span class="caret"></span>');
    }

    if ("comboFilters[Clients]" in partDic) {
        var cl = partDic["comboFilters[Clients]"].substring(1);
        $('.Client .dropdown-toggle').html(cl).append(' <span class="caret"></span>');
    }

    if ("comboFilters[Years]" in partDic) {
        var yr = partDic["comboFilters[Years]"].substring(1).slice(1);
        $('.Year .dropdown-toggle').html(yr).append(' <span class="caret"></span>');
    }
}, 1000);

这是标准的“请在1秒后运行此代码”模式。