防抖和节流

https://github.com/mqyqingfeng/Blog/issues/22

防抖

        <button id="btn">button</button>
    var btn = document.getElementById('btn')

    function payMoney() {
        console.log(11111);
    }

    btn.onclick = function () {
        let timer
        return function () {
            clearTimeout(timer)
            timer = setTimeout(() => {
                payMoney()
            }, 1000);
        }
    }()

节流

    // 节流
    // 随即色
    function coloring() {
        let r = Math.floor(Math.random() * 255);
        let g = Math.floor(Math.random() * 255);
        let b = Math.floor(Math.random() * 255);
        document.body.style.background = `rgb(${r},${g},${b})`
    }

    function throttle(func,delay) {
        let timer;
        return function () {
            let context = this;
            let args = arguments;
            if(timer){
                return
            }
            timer = setTimeout(() => {
                func.apply(context,args);
                timer = null
            }, delay);
        }
    }

    window.addEventListener('resize',throttle(coloring,1000))

 

posted @ 2021-10-25 16:03  从入门到入土  阅读(40)  评论(0编辑  收藏  举报