防抖和节流
防抖
最基础版本
function debounce(fn, wait) { let timer; return function () { if (timer) { clearTimeout(timer); } timer = setTimeout(() => { fn.apply(this, arguments); }, wait); }; }
立即触发和取消
function debouncePro(fn, wait, immediate = false) { let timer; function _debounce() { if (immediate && !timer) { fn.apply(this, arguments); timer = setTimeout(() => { timer = null; }, wait); return; } clearTimeout(timer); timer = setTimeout(() => { fn.apply(this, arguments); timer = null; }, wait); } _debounce.cancel = function () { clearTimeout(timer); timer = null; }; return _debounce; } // test const timer = (wait) => new Promise((resolve) => setTimeout(resolve, wait)); const fn = debouncePro(() => console.log(111), 1000, true); async function main() { fn(); console.log('第1次'); await timer(1000) fn(); console.log('第2次'); await timer(400) fn(); fn(); console.log('第3次延后触发'); } main();
节流
function throttle(fn, wait) { let timer return function() { if(timer) { return } timer = setTimeout(() => { fn.apply(this, arguments) timer = null }, wait); } } const timer = (wait) => new Promise((resolve) => setTimeout(resolve, wait)); const log = throttle(console.log.bind(console),1000) async function main() { log(11); await timer(1000) log(222); await timer(400) log(222); } main()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
上一篇: 实现简单路由
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
更多
发布评论