Skip to content

Instantly share code, notes, and snippets.

@danro
Last active June 21, 2016 04:38
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danro/7846358 to your computer and use it in GitHub Desktop.
Save danro/7846358 to your computer and use it in GitHub Desktop.
underscore throttle using requestAnimationFrame
// Returns a function, that, when invoked, will only be triggered once every
// browser animation frame - using tram's requestAnimationFrame polyfill.
// tram.js - https://github.com/bkwld/tram
_.throttle = function(func) {
var wait, args, context;
return function () {
if (wait) return;
wait = true;
args = arguments;
context = this;
window.tram.frame(function () {
wait = false;
func.apply(context, args);
});
};
};
@aaditmshah
Copy link

How about this:

function throttleAnimationFrame(cb, el) {
  var req, args, self, f = requestAnimationFrame;

  return function () {
    req || (req = f(chk, el));
    args = arguments;
    self = this;
  };

  function chk() {
    if (args && self) {
      req = f(chk, el);
      cb.apply(self, args);
    } else req = null;
    args = self = null;
  }
}

@yairEO
Copy link

yairEO commented Aug 2, 2015

it's not a throttle function if you can't control the time of callback firing.

it's more of a requestAnimationFrame which keeps calling itself..

@towry
Copy link

towry commented Jun 21, 2016

yairEO is right.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment