我只想使用$ interval(anyFunction(){},1000); 但1000的价值也应该是可变的。 如果我通过定义变量来改变它,则视图上的间隔不会改变。
有人可以发布一个例子来更新$ interval的'speed'吗?
非常感谢。
以防万一:
我的控制员:
$scope.food = 0;
var stop;
var farmInterval = 1000;
$scope.startFarming = function () {
console.log('farming started...');
if (angular.isDefined(stop)) return;
stop = $interval(function () {
$scope.food += 1;
}, farmInterval); // <-- this value 'farmInterval' should be variable
}
$scope.stopFarming = function () {
if (angular.isDefined(stop)) {
$interval.cancel(stop);
stop = undefined;
}
}
$scope.increaseFarmInterval = function () {
console.log(farmInterval);
if (farmInterval > 100) {
console.log('Increased by 50');
farmInterval -= 50;
} else {
console.log('maximum reached.');
}
}
我的观点:
<pre>{{food}}</pre>
<button class="btn btn-default" data-ng-click="startFarming()">Farm</button>
<button class="btn btn-default" data-ng-click="increaseFarmInterval()">Increase Farm Interval</button>
<button class="btn btn-danger" data-ng-click="stopFarming()">Stop</button>
Plunker-Version:http://plnkr.co/edit/V904pebWGvTWpyGMItwo?p=preview
答案 0 :(得分:0)
您需要使用$ timeout:
$scope.food = 0;
var farmInterval = 1000;
var shouldStop = true;
$scope.startFarming = function () {
console.log('farming started...');
shouldStop = false;
var loop = function () {
if (!shouldStop) {
$scope.food += 1;
$timeout(loop, farmInterval);
//defers another call to this function in a timeout
//on each "iteration" like this -actually it's not
//an interation- you can control what interval time to assign
}
};
}
$scope.stopFarming = function () {
shouldStop = true;
}
$scope.increaseFarmInterval = function () {
console.log(farmInterval);
if (farmInterval > 100) {
console.log('Increased by 50');
farmInterval -= 50;
} else {
console.log('maximum reached.');
}
}
注意我是如何在$ timeout调用链中转换$ timer的。这不仅是改变间隔的好方法,而且是当浏览器当天只实现setInterval
时脚本实现setTimeout
的唯一方法。
大多数代码已经是您的代码,但我修改了$timer
相关逻辑,不再使用$timer
,因此您必须注入$timeout
代替(或者 - 取决于您是否在控制器中的其他位置使用$timer
。
所以改变了逻辑:你没有杀死计时器。相反,你会阻止一个新的$timeout
迭代发生,因为 - 如果仔细观察 - 每个迭代都是在循环的中心逻辑之后显式创建的。