简体   繁体   中英

time remainder of setInterval JavaScript

I want to be able to run code on the condition that there is time left on a setInterval.

  let car = setInterval(function() {
    // stuff
  }, 2000);

  let vehicle = setInterval(function() {
    train()
  }, 1000);

  function train() {
    // stuff
    // and if car has time left, do this stuff too.
  }

At the last line of the train function, I want to check the car's time remaining but don't understand how to go about such a concept. I guess knowing the exact time left or simply that there is time left is the same to me so which ever is easier.

This is not going to be possible. Timers are actually executed outside of the JavaScript runtime and the time specified in them is never a precise measurement - - it's actually the minimum time that the timer could be expected to run. The actual amount of time depends on how busy the JavaScript runtime is and if the runtime is idle at the timer's timeout, the timer's callback function can be run.

So, essentially, you'd have to calculate how much longer the JavaScript execution stack will need in order to become idle, which you can't do because in order to get that time measurement, you have to execute the remaining code. So, you can't get the answer until there's no time left.

But, based on your code, it seems that you could just set a simple "flag" variable that gets set when car runs. So, inside train you can check to see if that flag has been set yet and if not, run the train code and then reset the flag.

Remember that timers are potentially quite imprecise, and that setInterval 's rules are...interesting...if your handler runs past when the next interval was meant to start. So important to keep in mind.

But if your goal is to know how long it's been since the start of the call to the timer vs when the timer is going to be set to fire again, it's a matter of remembering when you started

var start = Date.now();

...and then later checking how long it's been relative to the interval. For instance:

if (Date.now() - start >= 1900) {
    // It's been at least 1900ms since the start of the `vehicle` call,
    // so based on a 2000ms interval, in theory you have only 100ms left
}

But , again, note that timers can be quite imprecise if other things are keeping the UI thread busy.

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