Last active
September 20, 2020 06:57
-
-
Save zhanglun/e6b88b72b1b19b02323bcf0270520c0d to your computer and use it in GitHub Desktop.
debounce&throttle
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, wait, imediate) { | |
| let timer = null; | |
| return function (...args) { | |
| clearTimeout(timer); | |
| if (imediate && !timer) { | |
| fn.apply(this.args); | |
| } | |
| timer = setTimeout(() => { | |
| fn.apply(this, args); | |
| }) | |
| } | |
| } | |
| function throttle (fn, wait) { | |
| let previous = 0; | |
| return function (...args) { | |
| if (Date.now() - previous > wait) { | |
| previous = Date.now(); | |
| fn.apply(this, args); | |
| } | |
| } | |
| } | |
| function throttle2 (fn, wait) { | |
| let timer = null; | |
| return funciton (...args) { | |
| if (!timer) { | |
| timer = setTimeout(() => { | |
| timer = null; | |
| fn.apply(this, args); | |
| }) | |
| } | |
| } | |
| } | |
| function throttle3 (fn, wait) { | |
| let previous = 0; | |
| let timer = null; | |
| return function (...args) { | |
| if (Date.now() - previous > wait) { | |
| clearTimeout(timer); | |
| previous = Date.now(); | |
| fn.apply(this, args); | |
| } else if (!timer){ | |
| timer = setTimout(() => { | |
| timer = null; | |
| fn.apply(this, args); | |
| }, wait) | |
| } | |
| } | |
| } | |
| /* | |
| * options.leading 禁止第一次触发 default: false | |
| * options.trailing 禁止最后一次触发 default: false | |
| */ | |
| function throttle4 (fn, wait, options) { | |
| let previous = 0; | |
| let timer = null; | |
| return funcion (...args) { | |
| if (!previous && options.leading) { | |
| previous = Date.now(); | |
| } | |
| if (Date.now() - previous > wait) { | |
| clearTimeout(timer); | |
| previous = Date.now(); | |
| fn.apply(this, args); | |
| } else if (!timer && options.trailing) { | |
| timer = setTimeout(() => { | |
| previous = Date.now(); | |
| timer = null; | |
| fn.apply(this, args); | |
| }, wait) | |
| } | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment