首页 > Web开发 > 详细

JS的防抖与节流学习笔记

时间:2019-09-29 14:52:14      阅读:70      评论:0      收藏:0      [点我收藏+]

 

防抖(debounce):当持续触发事件时,在一定的时间段内,只有最后一次触发的事件才会执行。

例:

    function debounce(fn, wait) {
        var timer = null;
        return function() {
            if(timer !== null) {
                clearTimeout(timer);
            }
            timer = setTimeout(fn, wait);  
        }
    }
    function handle() {
        console.log(‘防抖处理!‘); 
    }
    window.addEventListener(‘scroll‘, debounce(handle, 1000));

 

节流(throttle):当持续触发事件时,已执行的事件在一定时间段内不会再次执行。实现节流有时间戳和定时器两种方式。

例:

// 时间戳:
    var throttle = function(func, delay) {
        var prev = Date.now();
        return function() {
            var now = Date.now();
            if (now - prev >= delay) {
                func();
                prev = Date.now();
            }
        }
    }
    function handle() {
        console.log(‘节流处理!‘);
    }
    window.addEventListener(‘scroll‘, throttle(handle, 1000));
// 定时器:
    var throttle = function(func, delay) {
        var timer = null;
        return function() {
            if (!timer) {
                timer = setTimeout(function() {
                    func();
                    timer = null;
                }, delay);
            }
        }
    }
    function handle() {
        console.log(‘节流处理!‘);
    }
    window.addEventListener(‘scroll‘, throttle(handle, 1000));

 

函数防抖和节流都是防止某一事件被频繁触发;区别:防抖是将多次执行变为最后一次执行,节流是将多次执行变为一段时间只执行一次


应用场景:窗口resize、页面scroll、拖拽、限时抢购、实时搜索等。

 

JS的防抖与节流学习笔记

原文:https://www.cnblogs.com/fengyuexuan/p/11607756.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!