Skip to content

Instantly share code, notes, and snippets.

@kevinweber
Last active December 23, 2016 17:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevinweber/f14b15e0954140a93aa28b7c6d422b2f to your computer and use it in GitHub Desktop.
Save kevinweber/f14b15e0954140a93aa28b7c6d422b2f to your computer and use it in GitHub Desktop.
Throttle
/**
* Throttle function
* based on https://remysharp.com/2010/07/21/throttling-function-calls
*/
function throttle(fn, threshold, scope) {
threshold = threshold || 250;
var last,
deferTimer;
return function () {
var context = scope || this,
now = +new Date(),
args = arguments;
if (last && now < last + threshold) {
clearTimeout(deferTimer);
deferTimer = setTimeout(function () {
last = now;
fn.apply(context, args);
}, threshold);
} else {
last = now;
fn.apply(context, args);
}
};
}
// Use it like this ...
$('body').on('mousemove', throttle(function (event) {
console.log('tick');
}, 1000));
/**
* Throttle function from Mozilla using requestAnimationFrame & customEvent
* Source: https://developer.mozilla.org/en-US/docs/Web/Events/resize
*/
(function () {
var throttle = function (type, name, obj) {
obj = obj || window;
var running = false;
var func = function () {
if (running) {
return;
}
running = true;
requestAnimationFrame(function () {
obj.dispatchEvent(new CustomEvent(name));
running = false;
});
};
obj.addEventListener(type, func);
};
throttle("resize", "optimizedResize");
throttle("orientationchange", "optimizedOrientationchange");
})();
// Use it like this ...
window.addEventListener(eventName, function () {
myFunction();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment