Skip to content

Instantly share code, notes, and snippets.

@yckart
Last active January 13, 2016 19:22
Show Gist options
  • Save yckart/6140932 to your computer and use it in GitHub Desktop.
Save yckart/6140932 to your computer and use it in GitHub Desktop.
throttle/debounce javascript
// call after last delay
function debounce(callback, delay) {
var timeout;
return function () {
var self = this, args = arguments;
if (timeout) clearTimeout(timeout);
timeout = setTimeout(function () {
callback.apply(self, args);
}, delay || 100);
};
}
module.exports = {
throttle: function (callback, delay) {
var timeout;
return function () {
if (timeout) return;
timeout = setTimeout(function () {
timeout = false;
}, delay || 100);
callback.apply(this, arguments);
};
},
debounce: function (callback, delay) {
var timeout, self, args;
return function () {
self = this;
args = arguments;
if (timeout) clearTimeout(timeout);
timeout = setTimeout(function () {
callback.apply(self, args);
}, delay || 100);
};
}
}
// call before each delay
function throttle(callback, delay) {
var timeout;
return function () {
if (timeout) return;
timeout = setTimeout(function () {
timeout = false;
}, delay || 100);
callback.apply(this, arguments);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment