js 防抖、节流

突发奇想,在触发事件的时候,一些会频繁触发的事件会不会造成资源的浪费或者大量的计算造成页面卡顿,比如onresize,onscroll,onmousemove等事件。

然后就引出了一个新知识点:防抖、节流

防抖:是指在事件触发结束后延时一段时间再去执行代码,如果在延时期间再次触发该事件,则重新计算延时时间。

例:浏览器触发onresize事件的时候,需要重新计算页面布局,在不防抖的情况下,不停的拖动浏览器窗口改变大小,浏览器就会不停的去计算,导致浪费大量的资源,加上防抖后,在触发事件后延时600毫秒才判断该事件结束,如果在600毫秒内再次触发了该事件,则重新计算600毫秒,直到判断事件结束之后才会触发;

代码如下:

//第一个参数为事件触发后需要执行的方法,第二个参数为延时时间
function
debounce(method, delay) { let timer = null; return function () { let context = this, args = arguments; if(timer){ clearTimeout(timer); timer = null; } timer = setTimeout(function () { method.apply(context, args); }, delay); } } let fun= debounce(() => { console.log('123'); }, 600); window.addEventListener('resize', fun);

节流:是指在规定时间内只触发一次事件,减少事件执行的频率;

例:实时判断input框中的内容是否合法,正常情况下,我们给input 绑定一个键盘弹起事件,弹起是时候去做判断,如果用户输入过快,则会去做多次判断。节流一秒的话就是指在一秒内不管用户输入多少次,都之后去判断一次,既不会影响用户体验,有达到了节流的目的

代码如下:

function throttle(func, wait) {
    let lastTime = null
    let timeout
    return function () {
        let context = this;
        let now = new Date();
        let arg = arguments;
        // 如果上次执行的时间和这次触发的时间大于一个执行周期,则执行
        if (now - lastTime - wait > 0) {
            // 如果之前有了定时任务则清除
            if (timeout) {
                clearTimeout(timeout)
                timeout = null
            }
            func.apply(context, arg)
            lastTime = now
        } else if (!timeout) {
            timeout = setTimeout(() => {
                // 改变执行上下文环境
                func.apply(context, arg)
            }, wait)
        }
    }
}
let quest = throttle(()=>{console.log("数据判断完成")},1000)
let btn = document.getElementsByTagName('button')[0];
btn.addEventListener('click',quest)

 使用方法和防抖相同

总结:一般情况下onresize,onkeyup事件使用防抖;onscroll、onmousemove等事件使用节流。

完工,困告。

猜你喜欢

转载自www.cnblogs.com/wubaiwan/p/11449547.html