如果在定时器的时间范围内再次触发,则不予理睬,等当前定时器完成,才能启动下一个定时器任务
1function throttle(fn, interval) { 2 let flag = true 3 return funtion(...args) { 4 let context = this 5 if (!flag) return 6 flag = false 7 setTimeout(() => { 8 fn.apply(context, args) 9 flag = true 10 }, interval) 11 }; 12};
也可以写成下面这样
1const throttle = function(fn, interval) { 2 let last = 0 3 return function (...args) { 4 let context = this 5 let now = +new Date() 6 // 还没到时间 7 if(now - last < interval) return 8 last = now 9 fn.apply(this, args) 10 } 11}
每次事件触发则删除原来的定时器,建立新的定时器,换言之,反复触发,那么只认最后一次,从最后一次触发开始计时
1function debounce(fn, delay) { 2 let timer = null 3 return function (...args) { 4 let context = this 5 if(timer) clearTimeout(timer); 6 timer = setTimeout(function() { 7 fn.apply(context, args) 8 }, delay) 9 } 10}
1function throttle(fn, delay) { 2 let last = 0, timer = null; 3 return function (...args) { 4 let context = this 5 let now = new Date() 6 if(now - last > delay){ 7 clearTimeout(timer) 8 setTimeout(function() { 9 last = now 10 fn.apply(context, args) 11 }, delay) 12 } else { 13 last = now 14 fn.apply(context, args) 15 } 16 } 17}