Last active
March 17, 2017 17:42
-
-
Save alexsasharegan/32b9e9ed2eb4bcc16d63d537e24ab526 to your computer and use it in GitHub Desktop.
Hijacking the useful debounce function from underscore.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function debounce( func, wait, immediate ) { | |
let timeout; | |
let args; | |
let context; | |
let timestamp; | |
let result; | |
const now = Date.now || () => new Date().getTime(); | |
const later = function () { | |
const last = now() - timestamp; | |
if ( last < wait && last >= 0 ) { | |
timeout = setTimeout( later, wait - last ); | |
} else { | |
timeout = null; | |
if ( !immediate ) { | |
result = func.apply( context, args ); | |
if ( !timeout ) context = args = null; | |
} | |
} | |
}; | |
return function () { | |
context = this; | |
args = arguments; | |
timestamp = now(); | |
const callNow = immediate && !timeout; | |
if ( !timeout ) timeout = setTimeout( later, wait ); | |
if ( callNow ) { | |
result = func.apply( context, args ); | |
context = args = null; | |
} | |
return result; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment