我希望能够每秒(或更快)重复调用一个函数。 假设“startdate”包含文本中的开始日期......在我的控制器中:
scope.arrayoftimes=[{time:XXXX},{time:XXXXXX}]
scope.startdate = $('#startingdate'); //start date comes from text in an element
scope.speed = 1000;
scope.index = 0;
scope.timer = $timeout(scope.doSomething(), scope.speed);
scope.doSomething = function() {
var currentTime = scope.startDate.html();
for (var i=scope.index; i < scope.arrayoftimes.length; i++) {
if(currentTime == roundTo(scope.arrayoftimes[i].time)) {
$rootScope.$emit('timeMatch', scope.index);
scope.index++;
break;
}
}
$timeout(scope.doSomething(), scope.speed);
}
上面的代码会在执行时释放我的浏览器。但是,如果我在scope.index ++之后或if条件内的任何地方坚持“警报”,那么它工作正常(只要我检查“防止打开多个对话框”)
scope.arrayoftimes=[{time:XXXX},{time:XXXXXX}]
scope.startdate = "//Insert Starting Date Here"
scope.speed = 1000;
scope.index = 0;
scope.timer = $timeout(scope.doSomething(), scope.speed);
scope.doSomething = function() {
var currentTime = scope.startDate;
for (var i=scope.index; i < scope.arrayoftimes.length; i++) {
if(currentTime == roundTo(scope.arrayoftimes[i].time)) {
$rootScope.$emit('timeMatch', scope.index);
scope.index++;
alert("alert"); // the existence of this alert message and checking prevent from opening more dialog boxes in chrome allows this to execute fine without freezing
break;
}
}
$timeout(scope.doSomething(), scope.speed);
}
发生了什么事?我怎么能绕过这个?有更好的方法吗?
答案 0 :(得分:0)
您的超时呼叫可能需要:
$timeout(function() { scope.doSomething(); }, scope.speed);
或
$timeout(scope.doSomething, scope.speed);
否则,您将立即执行doSomething(),从而导致无限循环。