Skip to content

Instantly share code, notes, and snippets.

@tcase360
Created April 27, 2019 17:57
Show Gist options
  • Save tcase360/f52cfb83be97eee2492b238939de42d8 to your computer and use it in GitHub Desktop.
Save tcase360/f52cfb83be97eee2492b238939de42d8 to your computer and use it in GitHub Desktop.
Debounce with an exit timeout
/**
* Create a function that accepts a function and then
* fires only after it hasn't been called for 250ms
*
* Once that is done, create an "exit" functionality
* that will take an "exit" number, higher than the
* "wait" variable, that will call the function regardless
*/
// params - fn, @{Callback}, wait @{Integer}
function debounce(fn, wait, exit) {
let timeout;
let called;
let originalTimestamp;
let timeSinceCalled;
return function() {
const functionCall = () => fn.apply(this, arguments);
if (!called) {
called = true;
originalTimestamp = Date.now();
} else {
timeSinceCalled = Date.now() - originalTimestamp;
}
// is the amount of wait milliseconds higher than the milliseconds left to exit?
// if true, set exit as variable to call timeout
// if false, set wait as timeout
const timeoutStamp = called && exit - timeSinceCalled < wait ? exit - timeSinceCalled : wait;
clearTimeout(timeout);
timeout = setTimeout(function() {
timeSinceCalled = 0;
called = false;
functionCall();
}, timeoutStamp);
}
}
const debounced = debounce(function() {
console.log('hello world');
}, 250, 750);
debounced();
debounced();
debounced();
debounced();
debounced();
setTimeout(debounced, 240);
setTimeout(debounced, 240 * 2);
setTimeout(debounced, 240 * 3);
setTimeout(debounced, 240 * 4);
setTimeout(debounced, 240 * 5);
setTimeout(debounced, 240 * 6);
setTimeout(debounced, 240 * 7);
setTimeout(debounced, 240 * 8);
setTimeout(debounced, 240 * 9);
setTimeout(debounced, 240 * 10);
setTimeout(debounced, 240 * 11);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment