在以下代码段中,我希望timeDiff可以在waitTime上设置。但我知道内部函数中的timeDiff只有在执行时才会获得值。如何使用元素的TIMEDIFF来设置给定函数的超时?
var timeDiff;
for (var i = 0; i < q.length; i++) {
(function() {
timeouts.push($timeout(function() {
var element = q.shift(); // q is a queue
timeDiff = element.TIMEDIFF;
console.log(element.TIMEDIFF); //3000
broadcastData(element);
}, waitingTime));
// console.log(timeDiff + " timeiff");
waitingTime = waitingTime + timeDiff; // 1000 + 3000
})();
}
简单来说,waitingTime应该依赖于element.TIMEDIFF。如何实现?
答案 0 :(得分:0)
这样的事情怎么样?我已经把它变得有点泛,但它应该做你希望实现的目标。 Example在这里。下一个函数的时间可以从当前正在执行的函数中完全配置。
var waitingTime = 100;
var q = {length: 100};
var i = 0;
var timeouts = [$timeout(getTimeDiff, waitingTime).then(callback)];
function callback(newTime) {
while(i < q.length) {
i++;
var promise = $timeout(getTimeDiff, newTime).then(callback);
timeouts.push(promise);
return promise;
}
}
function getTimeDiff() {
//here is where you would access the q and get the timediff
waitingTime += Math.floor(Math.random() * 100);
console.log(waitingTime + " until next tick");
return waitingTime;
}
答案 1 :(得分:0)
我已经改变了一点,我希望这适合你。
var timeDiff;
for (var i = 0; i < q.length; i++) {
var element = q[i];
timeDiff = element.TIMEDIFF;
timeouts.push(setTimeout(function(data) {
broadcastData(data.e);
}, waitingTime, {e:element}));
waitingTime = waitingTime + timeDiff;
}