问题描述:

I've faced the same problem a couple of times lately where I want something to happen on a particular moment in time. For example fire a midi note every quarter time, etc. Usually these get programmed by checking in every iteration of a loop something like this. In an event driven javascript world this would look like this:

on('tick', check);

function check(time) {

if (is_it_time(time)) {

do_your_thing();

}

}

Of course this if test gets executed way more often than is actually needed. I'm sure this is a common problem and I'm looking for a pattern or pointers to theory on this problem.

Edit: Should point out that this has nothing to do with actual time. The ticks I am receiving come not from the javascript real time clock. Maybe it would be interesting to hear how setTimeOut works under the hood. I can't imagine there is a if test every millisecond.

Edit2: The best thing I've come up with so far is hold a queue of functions for every every tick and cycle through them.

var tasks = new Array(96);

function check(ticks) {

tasks[ticks].forEach(function(task) {

task();

});

}

Since the number of tasks could grow large this is the most efficient I think.

网友答案:
function runAt(time, task) {
  var now = new Date();
  var delay = time - now;
  return setTimeout(task, delay);
}

runAt(Date.parse("2015-05-29T00:00:00+00:00"), function() {
  console.log("yo");
});
相关阅读:
Top