【js】實現3版函數節流

函數節流(throttle):當持續觸發事件時,保證一定時間段內只調用一次事件處理函數。節流通俗解釋就比如我們水龍頭放水,閥門一打開,水嘩嘩的往下流,秉着勤儉節約的優良傳統美德,我們要把水龍頭關小點,最好是如我們心意按照一定規律在某個時間間隔內一滴一滴的往下滴。

html

js

// 時間戳版
function throttle(func, wait) {
    let prevTime = 0;
    return () => {
        args = arguments;
        const _this = this;
        let nowTime = new Date().valueOf();
        if(nowTime - prevTime >= wait) {
            func.apply(_this, args);
            prevTime = nowTime
        } 
    }
}

// 顧尾不顧頭
// setTimeout版
function throttle2(func, wait) {
    let timer = null;
    return () => {
        // console.log('aaaa', arguments);
        const args = arguments;
        const _this = this;
        if(!timer) {
            timer = setTimeout(() => {
                console.log('????')
                func.apply(_this, args);
                timer = null;
            }, wait);
        }
    }
}

// 時間戳+setTimeout
function throttle3(func, wait) {
    let oldTime = 0;
    let timer = null;
    return () => {
        const _this = this;
        const args = arguments;
        const nowTime = new Date().valueOf();
        if(nowTime - oldTime > wait) {
            if(timer) {
                clearTimeout(timer);
                timer = null;
            }
            func.apply(_this, args);
            oldTime = nowTime;
        }

        if(!timer) {
            timer = setTimeout(() => {
                oldTime = new Date().valueOf();
                timer = null;
                func.apply(_this, args);
            }, wait);
        }
    }
}

const dom = document.getElementById('move');

function doSome() {
    console.log('執行拉');
}

const fn = throttle3(doSome, 500)
dom.addEventListener('mousemove', fn );
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章