10秒后停止执行setInterval函数

时间:2019-01-08 06:59:18

标签: javascript jquery html

我有一个脚本,每2秒检查一次DOM是否有类(.discount__value),并在找到后附加HTML代码。

        var discountWDollar = $(".discount__value:last").text();
        var discount1 = discountWDollar.replace(/\$/g,''); //remove $ sign
        var discount = Math.abs(discount1); //convert to positive number

        var cartSubTotalWDollar = $(".cart__subtotal").text();
        var cartSubTotal = cartSubTotalWDollar.replace(/\$/g,''); //remove $ sign

        newTotal1 = cartSubTotal - discount; //new total
        var discountedTotal = newTotal1.toPrecision(4); //add decimal number(centavo)


        var checkExist = setInterval(function() {
            if ($(".discount__value")[1]) {
                $(".cart-subtotal-wrapper").append("<div class='newTotalLabel'><span class='label'>Total on Check Out</span> <span class='value'>$"+discountedTotal+"</span></div>");

            clearInterval(checkExist);
        } else { 
            console.log("retry");
        }
    }, 2000); // check every 2secs

该代码有效,但是如果该类不存在,它将继续搜索DOM,我希望它在10秒后停止搜索。请帮助编码大师?

2 个答案:

答案 0 :(得分:2)

使用计数器并在计数器达到限制时清除计时器:

var counter = 1;
var checkExist = setInterval(function() {
      if ($(".discount__value")[1]) {
        $(".cart-subtotal-wrapper").append("<div class='newTotalLabel'><span class='label'>Total on Check Out</span> <span class='value'>$" + discountedTotal + "</span></div>");

        clearInterval(checkExist);
      } else {
        if (counter === 5) {
          clearInterval(checkExist);
        }
        counter++;
      }, 2000);

答案 1 :(得分:1)

这可能会有所帮助,请使用10秒钟的设置超时时间

var checkExist = setTimeout(function(){setTimeoutsetInterval(function() {
                if ($(".discount__value")[1]) {
                    $(".cart-subtotal-wrapper").append("<div class='newTotalLabel'><span class='label'>Total on Check Out</span> <span class='value'>$"+discountedTotal+"</span></div>");

                clearInterval(checkExist);
            } else { 
                console.log("retry");
            }
        }, 2000);   }, 10000);