Created
November 28, 2021 04:14
-
-
Save vv13/2c3f209b247a8713a07e824dd18e7cb8 to your computer and use it in GitHub Desktop.
JavaScript 节流函数
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
function throttle(fn, delay) { | |
let lock = false; | |
return (...args) => { | |
if (lock) return; | |
lock = true; | |
setTimeout(() => { | |
lock = false; | |
fn(args) | |
}, delay) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
“节流”就是降低任务执行频率,在指定的时间间隔内只允许一次任务的触发。比如在下拉滚动事件中,我们需要判断滚动条距离屏幕顶部的高度,若没有节流函数时,则每次滚动都会触发大量的计算操作,通过节流函数,可以让这类连续触发的任务得到很好的性能提升。
在JavaScript中,其实我们通过一个标志位即可解决节流的问题。我们将标志位开做一个门,当一个房间只能容纳下1个人时,若房间没有人,则门是开着的;如果人进去以后会把门关上,这时其他人就无法再进来;等人离开时会将门打开,其他人才可以进来。