We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
相信大家对这两个词都不陌生,面试中经常会问答,我也在很早之前就去学习和了解过了,今天再次进行回顾和总结(主要是最近在工作中时常用到😜)
防抖:触发高频事件后n秒内函数只会执行一次,如果n秒内高频事件再次被触发,则重新计算时间
节流:高频事件触发,但在n秒内只会执行一次,所以节流会稀释函数的执行频率
这两个技巧主要是用在一些高频操作的场合,比如input事件、scroll事件、resize事件等等
/** * 防抖工厂 * @param {Function} fn 需要防抖的函数 * @param {Date} time 时间间隔,默认500ms * @returns {Function} */ function debounce(fn, time = 500) { let timer = null; return function(...rest){ clearTimeout(timer); timer = setTimeout(() => { fn.apply(this, rest); },time) } } /** * 节流工厂 * @param {Function} fn 需要节流的函数 * @param {Date} time 时间间隔,默认500ms * @returns {Function} */ function throttle(fn, time = 500) { let startTime = new Date(); return function (...rest) { let time_ = (new Date() - startTime) >= time; if(!time_)return; fn.apply(this, rest); startTime = new Date(); } }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
每日一题之防抖和节流
相信大家对这两个词都不陌生,面试中经常会问答,我也在很早之前就去学习和了解过了,今天再次进行回顾和总结(主要是最近在工作中时常用到😜)
总结
实现思路:通过定时器来延迟执行,如果在n秒内,就清除定时器
实现思路:通过比对时间差值来完成判断是否执行函数
这两个技巧主要是用在一些高频操作的场合,比如input事件、scroll事件、resize事件等等
ps:防抖我是用的我比较习惯的一种思路,网上有第二种思路,就是通过标识符和定时器的延迟执行来实现,具体代码可以看KouYidong的解答
The text was updated successfully, but these errors were encountered: