Skip to content
New issue

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

第 3 题:什么是防抖和节流?有什么区别?如何实现? #3

Open
Hanpoung opened this issue May 10, 2019 · 0 comments

Comments

@Hanpoung
Copy link
Owner

Hanpoung commented May 10, 2019

每日一题之防抖和节流

相信大家对这两个词都不陌生,面试中经常会问答,我也在很早之前就去学习和了解过了,今天再次进行回顾和总结(主要是最近在工作中时常用到😜)

总结

防抖:触发高频事件后n秒内函数只会执行一次,如果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();
 }
}
ps:防抖我是用的我比较习惯的一种思路,网上有第二种思路,就是通过标识符和定时器的延迟执行来实现,具体代码可以看KouYidong的解答
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant