【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 );

你可能感兴趣的:(JavaScript学习之路,前端面试)