简体   繁体   English

访问超时函数内的变量

[英]Accessing a variable inside a timeout function

In the following code segment I want timeDiff to be available to be set on waitingTime. 在以下代码段中,我希望timeDiff可以在waitingTime上设置。 But I understand that timeDiff inside the inner function would get value only when it's getting executed. 但我明白内部函数中的timeDiff只有在执行时才会获得值。 How to use element's TIMEDIFF to set timeout for the give function? 如何使用element的TIMEDIFF为give函数设置超时?

  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
      })();
  }

In simple terms waitingTime should depend on element.TIMEDIFF. 简单来说,waitingTime应该依赖于element.TIMEDIFF。 How to achieve that? 怎么实现呢?

What about something like this? 这样的事情怎么样? I've made it a bit generic, but it should do what you're hoping to achieve. 我已经把它变得有点泛,但它应该做你希望实现的目标。 Example here. 这里的例子 The time for the next function and is completely configurable from within the currently executing function. 下一个函数的时间可以在当前执行的函数中完全配置。

  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;
  }

I've changed a little bit, I hope that works for you. 我改变了一点,希望对你有用。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM