首页 > 其他 > 详细

节流和防抖

时间:2020-01-05 23:38:39      阅读:123      评论:0      收藏:0      [点我收藏+]

作用:减少调用频率,减轻浏览器负担,提高用户体验

场景:

  函数防抖(debounce):当持续触发事件时,在一定时间(wait)内没有再次触发,则执行处理函数。若在期间有触发了事件,那么重当前时间开始重新计时。(搜索框)

  节流(throttle):一定时间段内只能触发一次处理函数

函数防抖实现:

function debounce(fn, wait) {
    var timeout = null;
    return function() {
        clearTimeout(timeout);
        timeout = setTimeout(fn, wait);
    }
}
// 处理函数
function handle() {
    console.log(Math.random()); 
}
// 滚动事件
window.addEventListener(‘scroll‘, debounce(handle, 1000));

 

函数节流实现:

 
定时器实现--第一次先等待再 执行
var throttle = function(func, delay) {
            var timer = null;
            return function() {
                var context = this;
                var args = arguments;
                if (!timer) {
                    timer = setTimeout(function() {
                        func.apply(context, args);
                        timer = null;
                    }, delay);
                }
            }
        }
        function handle() {
            console.log(Math.random());
        }
        window.addEventListener(‘scroll‘, throttle(handle, 1000));
     2.时间戳实现---第一次先执行    
        function throttle(func,wait){
            var lastTime = 0;
            return function(){
                var nowTime = +new Date();
                if(nowTime -lastTime >wait){
                    func.apply(this,arguments);
                    lastTime = nowTime;
                }
            }
        } 

节流和防抖

原文:https://www.cnblogs.com/freefy/p/12153978.html

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