防抖&節流

防抖:你狂點按鈕也沒有,等你冷靜下來事件纔會觸發。
節流:遊戲裏面的技能冷卻功能。app

//防抖例子1 function debounce(fn,delay=200){this

    let timer = null;遊戲

     return function(){事件

        if(timer) clearTimeout(timer);it

        timer = setTimeout(()=>{io

            fn.apply(this,arguments);function

            timer = null; },delay);定時器

        }im

    }時間戳

}

//例子2

function debounce(func, wait) {

    let timeout;

    return function () {

        let context = this;

        let args = arguments;

        if (timeout) clearTimeout(timeout);

        timeout = setTimeout(() => {

            func.apply(context, args) }, wait);

        }

    }

}

節流

//時間戳版

function throttle(func, wait) {

    let previous = 0;

    return function() {

        let now = Date.now();

        let context = this;

        let args = arguments;

        if (now - previous > wait) {

            func.apply(context, args);

            previous = now;

        }

    }

}

//定時器版

function throttle(func, wait) {

    let timeout;

    return function() {

        let context = this;

        let args = arguments;

        if (!timeout) {

            timeout = setTimeout(() => {

                timeout = null;

                func.apply(context, args) }, wait)

         }

    }

}

相關文章
相關標籤/搜索