首页 > Web开发 > 详细

js防抖和节流应用

时间:2020-09-29 15:57:05      阅读:33      评论:0      收藏:0      [点我收藏+]

节流(throttle),防抖(debounce)都是为了限制函数的多次执行,造成页面出现延迟,假死或卡顿的现象,过多的资源浪费一种优化方案

函数防抖 debounce
防抖是指在连续事件触发后在规定时间只会最后执行一次函数,如果连续事件再次被触发,则重新计算时间。

例子:window触发resize的时候,不断的调整浏览器窗口大小会不断的触发这个事件,用防抖来让其只触发一次

代码示例

function debounce(fn,delay) {
    var timeout = null; // 创建存放定时器的返回值
    return function (e) {
        // 把前一个 setTimeout 清楚掉,确保只执行一次
        clearTimeout(timeout); 
        timeout = setTimeout(() => {
            fn();
        }, delay);
    };
}
window.addEventListener(‘scroll‘, debounce(handle, 1000));

函数节流 throttle
throttle是指连续触发事件多次执行变成每隔一段时间执行,节流会稀释函数的执行频率

例子: 监听滚动事件,比如是否滑到底部自动加载更多,用throttle来判断

代码示例

 function throttle(fun, delay) {
        let last, deferTimer
        return function (args) {
            let that = this
            let _args = arguments
            let now = +new Date()
            if (last && now < last + delay) {
                clearTimeout(deferTimer)
                deferTimer = setTimeout(function () {
                    last = now
                    fun.apply(that, _args)
                }, delay)
            }else {
                last = now
                fun.apply(that,_args)
            }
        }
    }
 
    let throttleAjax = throttle(ajax, 1000)
 
    let inputc = document.getElementById(‘throttle‘)
    inputc.addEventListener(‘keyup‘, function(e) {
        throttleAjax(e.target.value)
    })

js防抖和节流应用

原文:https://www.cnblogs.com/visugar/p/13748816.html

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