zoukankan      html  css  js  c++  java
  • js节流和防抖

    节流:用于频繁请求操作例如change,click,保证某些代码不可以在没有间断的情况下连续重复执行,第一次调用,会创建一个定时器,在指定的时间间隔之后执行代码。当第二次调用时,它会清除前一次的定时器并设置新的一个,如果前一个定时器已经执行过了,这个操作就没有意义。然而,如果前一个定时器尚未执行,其实就是将其替换成一个新的定时器。目的是只有在执行函数的请求停止了一段时间之后执行。

    //初级方案
    let btn=document.querySelector('.btn')
    
        let timer=null
        btn.onclick=function(){
            clearTimeout(timer)
            timer=setTimeout(()=>{
                console.log('发起请求')
            },1000)
        }
    //封装复用
    let event = function (mouseEvent) {
                console.log('发起请求' + mouseEvent)
            }
    
            function throttle(event, time) {
                let timer = null
                return function (...args) {
                    clearTimeout(timer)
                    timer = setTimeout(() => {
                        event.apply(this, args)
                    }, time)
                };
            }
            btn.addEventListener('click', throttle(event, 1000))
    //优化
     btn.onclick = (function () {
                let timer = null
                return function(mouseEvent){
                clearTimeout(timer)
                timer = setTimeout(() => {
                    console.log('发起请求')
                }, 1000)
                }
            })()

    防抖:对于高密度操作例如resize,scroll,不管事件触发频率多高,都保证按一定的时间间隔应答

    //初级方案
    let flag = true
            window.onscroll = function () {
                if (flag) {
                    flag = false
                    setTimeout(() => {
                        console.log('刷新')
                        flag = true
                    }, 3000)
                }
            }
     //优化
    window.onscroll = (function () {
                let flag = true
                return function () {
                    if (flag) {
                        flag = false
                        setTimeout(() => {
                            console.log('刷新')
                            flag = true
                        }, 3000)
                    }
                }
            })()
     
  • 相关阅读:
    面向对象的继承关系体现在数据结构上时,如何表示
    codeforces 584C Marina and Vasya
    codeforces 602A Two Bases
    LA 4329 PingPong
    codeforces 584B Kolya and Tanya
    codeforces 584A Olesya and Rodion
    codeforces 583B Robot's Task
    codeforces 583A Asphalting Roads
    codeforces 581C Developing Skills
    codeforces 581A Vasya the Hipster
  • 原文地址:https://www.cnblogs.com/shirleysblog/p/13334123.html
Copyright © 2011-2022 走看看