在范围内更改值时删除计时器

Remove timer on change of value in scope

我的 angular 控件中有以下代码

scope.$watch(function(){ return scope.state; }, function() {
    var t1 = scope.state;
        var Interval = setInterval(function(){ Timer() }, 2500);
        if(t1 != "b"){
            clearInterval(Interval);
        }

        function Timer() {
            console.log(t1);
        }
});

我的预期是一旦 t1 变为 "b",定时器应该停止打印。无法理解 t1 一直打印的原因,就好像清除间隔从未发生过一样。如果这是错误的,正确的做法是什么。

因为t1只检查了一次。您设置间隔,并在设置间隔后立即查看变量是否为 "b",然后就是它。如果变量在那一刻不 "b" ,它将永远不会被清除。

再次调用观察器时,您创建一个新的间隔并重新运行该检查。如果变量 "b" 现在,它将终止该间隔,它不会对上次调用时创建的间隔做任何事情。

你可能想要这样的东西,你只在第一次创建间隔时创建它。

scope.$watch(function() { return scope.state; }, function() {
  var t1 = scope.state;
  if (!scope.myInterval) {  //if there is no interval create it
    function timer() {
      console.log(t1);
    }
    scope.myInterval = setInterval(timer, 2500);
  }
  if (t1 != "b") {
    clearInterval(scope.myInterval);
    //delete scope.myInterval;
  }

});

并且由于您使用的是 angular,您可能应该使用他们的 $interval.

而且不在范围内...

var myInterval;
scope.$watch(function() { return scope.state; }, function() {
  var t1 = scope.state;
  if (!myInterval) {  //if there is no interval create it
    function timer() {
      console.log(t1);
    }
    myInterval= setInterval(timer, 2500);
  }
  if (t1 != "b") {
    clearInterval(myInterval);
    myInterval = null;
  }

});