debounce 防抖
简单来说,就是放抖动。
当持续触发事件时,
debounce
会合并事件且不会去触发事件,当一定时间内没有触发再这个事件时,才真正去触发事件。1debounce(fn, 1000); //1秒内没有触发这个事件才执行下面是
debounce
的简单实现:1234567891011121314151617181920function debounce(fn, delay) {let timer;let ctx;let args;const execute = function() {fn.apply(ctx, args);};return function() {ctx = this;args = arguments;if (timer) {clearTimeout(timer);}timer = setTimeout(execute, delay);};}throttle 节流
当持续触发事件时,保证隔间时间触发一次事件。
1throttle(fn, 1000); // 一秒内只触发一次。需要注意的是,比如你一秒内按了两下以上,那么将触发两次下面是
throttle
的简单实现:12345678910111213141516171819202122232425262728293031323334function throttle(fn, delay) {let ctx;let args;let timer;let now;let previous;const execute = function() {fn.apply(ctx, args);previous = now;};return function() {ctx = this;args = arguments;now = Date.now();if (timer) {clearTimeout(timer);}const diff = now - (previous + delay);if (previous) {if (diff >= 0) {execute();} else {timer = setTimeout(execute, -diff);}} else {execute();}};}根据实际业务场景,合理的利用
debounce
(防抖)和throttle
(节流)可以优化性能和提高用户体验。两者间的核心区别就在于持续触发事件时,前者合并事件并在最后时间去触发事件,而后者则是隔间时间触发一次。参考