Created
November 14, 2018 06:36
-
-
Save hectorguo/517606c7bcee57d46520b27d04a26712 to your computer and use it in GitHub Desktop.
throttle without using setTimeout (only last run)
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 throttle(fn, rate) { | |
let oldTime; | |
let timer; | |
function helper(...args) { | |
const now = Date.now(); | |
// first time: need to call fn once | |
if(!oldTime || now - oldTime > rate) { | |
const result = fn.apply(this, args); | |
oldTime = now; | |
clearTimeout(timer); // clear the last one if fn has already been called | |
return result; | |
} | |
// last call if it hasn't reached to rate | |
clearTimeout(timer); | |
timer = setTimeout(() => { | |
fn.apply(this, args); | |
oldTime = Date.now(); // refresh oldTime | |
}, rate - (now - oldTime)); | |
} | |
return helper; | |
} | |
// Test 1: | |
// const doWithThrottle = throttle((i) => { | |
// console.log(i) | |
// }, 5000); | |
// for(let i = 0; i< 100; i++) { | |
// doWithThrottle(i); | |
// } | |
// output: 0, after 5 seconds, 99 | |
// Test 2: | |
// let i = 0; | |
// const timer = setInterval(() => { | |
// doWithThrottle(i++); | |
// }, 100); | |
// output: 0, 50, 100, ... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment