HTML5.MicIO icon indicating copy to clipboard operation
HTML5.MicIO copied to clipboard

Swap setInterval for requestAnimationFrame

Open pete-otaqui opened this issue 10 years ago • 1 comments

Hi,

setInterval is usually pretty poor for timing things.

You should get better performance by using requestAnimationFrame(). This will run at a maximum of 60fps, depending on how "busy" the rest of the system is. The latter qualification is also true of setInterval of course since javascript is single threaded.

In general you would do something like this:

function requestInterval(fn, ms) {
  var handle = {value: null};
  var timeStart = new Date().getTime();
  var rafFn = function() {
    var timeNow = new Date().getTime();
    if ( timeNow >= timeStart + ms ) {
      fn();
      timeStart = timeNow; // or maybe timeStart += ms?
    }
    handle.value = requestAnimationFrame(rafFn);
  };
  handle.value = requestAnimationFrame(rafFn);
  return handle;
}

// use it:
var handle = requestInterval(function() {console.log(Date.now());}, 1000);

// cancel it:
cancelAnimationFrame(handle.value);

I haven't tested that code, and I also assume that requestAnimationFrame is unprefixed. There are decent shims out there you could look at to, such as:

https://gist.github.com/joelambert/1002116

pete-otaqui avatar Mar 25 '14 09:03 pete-otaqui

That would have made things a lot easier. I'll have to try that out when I have a chance...which is probably either this weekend or next. Sr. Design/School work has me swamped.

cobookman avatar Mar 25 '14 12:03 cobookman