Last active
August 17, 2016 15:04
-
-
Save zeusdeux/b1703412b6a8f5bd6643184e83eeebae to your computer and use it in GitHub Desktop.
Debounce and throttle?
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
// If multiple calls to fn are made within time t | |
// this will call fn only once after a delay of | |
// t milliseconds after the most recent call | |
function debounce1(fn, t) { | |
let timeout | |
return function (...args) { | |
let self = this | |
clearTimeout(timeout) | |
timeout = setTimeout(() => fn.apply(self, args), t) | |
} | |
} | |
// this will call fn only once within an interval of time t | |
// it will call fn with the arguments provided in the | |
// most recent call before the timer expires | |
// Is this throttle? | |
function debounce2(fn, t) { | |
let timeout = null | |
let latestSelf, latestArgs | |
return function (...args) { | |
latestSelf = this | |
latestArgs = args | |
if (timeout) return | |
timeout = setTimeout(() => { | |
fn.apply(latestSelf, latestArgs) | |
timeout = null | |
}, t) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment