Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Swap setInterval for requestAnimationFrame #3

Open
pete-otaqui opened this issue Mar 25, 2014 · 1 comment
Open

Swap setInterval for requestAnimationFrame #3

pete-otaqui opened this issue Mar 25, 2014 · 1 comment

Comments

@pete-otaqui
Copy link

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

@cobookman
Copy link
Owner

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants