JS 节流

作者: 云龙789 | 来源:发表于2019-02-21 19:37 被阅读0次
    <script>
        /**
         *
         * @param idle number 空闲时间 单位毫秒
         * @param action 请求关联函数,实例用用需要调用的函数
         */
        // const debounce = (fn, time) => {
        //     let timeout;
        //
        //     return function () {
        //         const functionCall = () => fn.apply(this, arguments);
        //
        //         clearTimeout(timeout);
        //         timeout = setTimeout(functionCall, time);
        //     }
        // }
    //  上面的 debounce  和下面的结果都是一样的
       let debounce =  function( fn,delay) {
            let timerId;
            return function (...args) {
                if (timerId) {
                    clearTimeout(timerId);
                }
                timerId = setTimeout(() => {
                    fn(...args);
                    timerId = null;
                }, delay);
            }
        }
        window.addEventListener('keyup', debounce((e) => {
            console.log(e.code);
        }, 300));
    </script>
    

    debounce 函数是从松手那一刻开始,300 毫秒之后才会打印出东西

    image.png

    不论你按多少此按键,只会打印最后一次按的键。
    达到的效果就是按键在300毫秒的时间内,不管按多少次按键,都只会限制最后一次按的,
    但是300秒之后,可以再次按

    • 如果是手机段想要在手触摸按钮后,松手 1秒 才可以再次操作,可以这样
    document.getElementById('button').ontouchstart = debounce((e) => {
            console.log(e);
        }, 1000)
    

    相关文章

      网友评论

        本文标题:JS 节流

        本文链接:https://www.haomeiwen.com/subject/azmdyqtx.html