简体   繁体   中英

Accessing a variable inside a timeout function

In the following code segment I want timeDiff to be available to be set on waitingTime. But I understand that timeDiff inside the inner function would get value only when it's getting executed. How to use element's TIMEDIFF to set timeout for the give function?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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