这是因为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;
}
});
而且,由于您使用的角度,你应该使用他们的$ 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;
}
});
因为T1只检查一次......你设置的时间间隔,你让后马上看到如果变量是“B”,比它是。如果该变量在该瞬间不是“b”,它将永远不会被清除。 – epascarello
但我有我的功能在看,我在想t1! =“b”将在scope.state的$ watch变成“b”时被验证。 – user2934433
阅读下面的答案,我添加了更多关于发生的事情的细节。 – epascarello