weixin_33691817 2017-02-25 21:43 采纳率: 0%
浏览 184

JS <(小于)运算符失败

I have a script that AJAXes a request every 10 seconds (but technically 11), for the user. I have a simple countdown made from 10 to 0 and then again and again.

This countit function is called after each AJAX request to restart

Here is my code:

function countit() {
  var count = 10;
  loading = setInterval(function() {
    $(box).val("Will automatically check in " + count + "second(s), please DO NOT refresh the page yourself.");
    count--;
    if (count <= 0) {
      clearInterval(loading);
    }

  }, 1000);
}

The code works fine except, if you leave the page and come back, the countdown proceeds into negative and does not stop. Here is the image:

enter image description here

I cant be sure if this is a problem with the code or JS but the counter doesnt go below 0 when the user stays on the page.

  • 写回答

1条回答 默认 最新

  • 游.程 2017-02-25 22:08
    关注

    As Ibrahim & Chris have said:

    Add a var infront of the Interval as without it, the variable is global.

    function countit() {
        var count = 10;
        var loading = setInterval(function() {
            $(box).val("Will automatically check in " + count + "second(s), please DO NOT refresh the page yourself.");
            count--;
            if (count <= 0) {
                clearInterval(loading);
            }
        }, 1000);
    }
    
    评论

报告相同问题?