关于javascript:SetInterval / ClearInterval循环无法正常运行

SetInterval/ClearInterval loop not functioning correctly

我知道这个问题之前已经回答过,但是其他答案似乎都不能完全解决我的问题。 我有一个计时器函数,在调用时应该使用setInterval每秒运行5秒,然后停止。 这一次可以工作,但是clearInterval似乎不起作用,因为倒计时循环的后半部分继续运行。 我觉得这是一个范围错误,但是我尝试将setInterval和clearInterval移到函数外部没有任何运气。 这是我的代码-在单击按钮时调用此函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
var startGame = function(){
  var count = 5;

  var countdownTimer = function(){
    setInterval(countdown, 1000);
  };

  var countdown = function(){
    if (count > 0){
      console.log('inside counter loop');
      count--;
      $('.timer').text('0:' + count);
    } else {
        clearInterval(countdownTimer);
        console.log('inside endGame loop');
        //endgame(); //This should run once when the timer reaches 0.
     }
  };

    countdownTimer();

};

现在,该循环将正确运行一次,然后每秒进行一次console.log" inside endGame循环"而无需重置。 我希望循环运行一次,然后停止,然后等待重新启动,直到单击处理程序再次调用该函数为止。


setInterval()返回您需要存储并使用clearInterval()的时间间隔ID

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var startGame = function() {
    var count = 5;
    var intervalID ;
    var countdownTimer = function() {
        //Store the intervalID
        intervalID = setInterval(countdown, 1000);
    };
    var countdown = function() {
        if (count > 0) {
            console.log('inside counter loop');
            count--;
            $('.timer').text('0:' + count);
        } else {
            if (intervalID) {
                //Pass currect pointer
                clearInterval(intervalID);
            }
        }
    };
    countdownTimer();
};