Created
February 27, 2019 01:48
-
-
Save mnikn/8244a146b8aff78d27c779a60245d8ea to your computer and use it in GitHub Desktop.
[debounce] debounce and throttle #utils
This file contains hidden or 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(fn, delay) { | |
let timer = setTimeout(fn, delay); | |
return function(){ | |
clearTimeout(timer); | |
fn.apply(this, arguments); | |
}; | |
} | |
function throttle(fn, delay) { | |
let timer = setTimeout(fn, delay); | |
let startTime = new Date(); | |
return function() { | |
clearTimeout(timer); | |
let currentTime = new Date(); | |
if(currentTime - startTime > delay) { | |
fn.apply(this, arguments); | |
startTime = currentTime; | |
} else { | |
timer = = setTimeout(fn, delay); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment