Skip to content

Instantly share code, notes, and snippets.

@jackson-sandland
Created June 18, 2018 17:13
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 jackson-sandland/ecfe0ad5c05e9711d42d2f6d4b2f8c61 to your computer and use it in GitHub Desktop.
Save jackson-sandland/ecfe0ad5c05e9711d42d2f6d4b2f8c61 to your computer and use it in GitHub Desktop.
// decorator to only allow function call after the timer is done.
const throttle = (func, delay) => {
let timeout;
return function() {
const context = this;
const args = arguments;
if (!timeout) {
func.apply(context, args);
timeout = true;
setTimeout(() => timeout = false, delay);
}
}
}
// decorator to catch the last fired event when throttling
const throttle = (func, delay) => {
let lastRan;
return function() {
const context = this;
const args = arguments;
if (!lastRan) {
func.apply(context, args);
lastRan = Date.now();
} else {
setTimeout(function(){
if ((Date.now() - lastRan) >= delay) {
func.apply(context, args);
lastRan = Date.now();
}
}, delay - (Date.now() - lastRan));
}
}
}
// decorator to queue all invocations and execute them at each timeout
const throttle = (func, delay) => {
let lastRan;
function wrapper() {
const context = this;
const args = arguments;
wrapper.calls.push(args);
if (!lastRan) {
func.apply(context, args);
wrapper.calls.shift();
lastRan = Date.now();
} else {
const queue = function() {
if (wrapper.calls.length > 0) {
if ((Date.now() - lastRan) >= delay) {
setTimeout(function() {
func.apply(context, args);
wrapper.calls.shift();
lastRan = Date.now();
}, delay - (Date.now() - lastRan));
}
}
setTimeout(queue, delay);
}
queue();
}
}
wrapper.calls = [];
return wrapper;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment