JavaScript-防抖和节流

防抖(debounce):如果一个函数持续地触发,那么只在它停止触发的一段时间后才执行,如果在这段时间内又开始持续触发,则重新计算时间。

防抖函数的实现如下:

function debounce(func, wait){
    let timeout;
    return function() {
        clearTimeout(timeout);
        timeout = setTimeout(() => {
          func.apply(this, arguments);
        }, wait);
    };
}


// 使用示例
const debouncedFunction = debounce(() => {
    console.log('Debounced function executed');
}, 300);

window.addEventListener('resize', debouncedFunction);

节流(throttle):如果一个函数持续地触发,那么固定在一段时间内只执行一次。

节流函数的实现如下:

function throttle(func, wait) {
    let lastTime = 0;
    return function() {
        let now = Date.now();
        if (now - lastTime > wait) {
        func.apply(this, arguments);
        lastTime = now;
        }
    };
}


// 使用示例
const throttledFunction = throttle(() => {
    console.log('Throttled function executed');
}, 1000);

window.addEventListener('scroll', throttledFunction);

防抖和节流的区别:

  • 防抖是让连续触发的函数在一段时间后只执行一次,如果在这段时间内又触发了该函数,则重新计算时间。

适用场景:文本输入的验证(连续输入文字后发送Ajax请求进行验证,验证一次就好)。

  • 节流是让连续触发的函数在一段时间内只执行一次,并且这段时间内的多次触发只会计算一次。

适用场景:滚动加载,时间间隔内只加载一次,模拟鼠标移动(mousemove),监听滚动事件(比如是否滑到底部自动加载更多,用throttle是为了降低频率)。

  • 防抖:事件触发后,只有在一段时间内没有再触发事件,处理函数才会执行。
  • 节流:事件触发后,按照设定的时间间隔执行处理函数,频繁触发事件时也不会立即重复执行处理函数。

你可能感兴趣的:(javascript,开发语言)