Created
January 20, 2016 22:58
-
-
Save btmills/0d85d580b53cc1e02ec6 to your computer and use it in GitHub Desktop.
Throttle function
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
const Throttle = (delay = 30) => { | |
let timer = null; | |
let start = null; | |
return (cb) => { | |
if (start) { | |
const remaining = delay - (Date.now() - start); | |
clearTimeout(timer); | |
timer = setTimeout(() => { | |
cb(); | |
timer = null; | |
start = Date.now(); | |
}, remaining); | |
} else { | |
cb(); | |
timer = setTimeout(() => { | |
timer = null; | |
start = null; | |
}, delay); | |
start = Date.now(); | |
} | |
}; | |
}; | |
const throttle = new Throttle(1500); | |
window.onkeydown = (event) => throttle(() => console.log(event.keyCode)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment