Skip to content

Instantly share code, notes, and snippets.

@danro
Last active May 6, 2024 05:18
Show Gist options
  • Select an option

  • Save danro/7846358 to your computer and use it in GitHub Desktop.

Select an option

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
Copy Markdown

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

yairEO commented Aug 2, 2015

Copy link
Copy Markdown

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

towry commented Jun 21, 2016

Copy link
Copy Markdown

yairEO is right.

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