JavaScript防抖(Debouncing)和节流(Throttling)

防抖(Debouncing)

假设你正在坐公交,当公交到站后接到人准备启动车之前发现还有乘客要乘车,这时公交司机会按下开门开关,然后让乘客上公交;
如果在坐公交关门之前,又有人来了,司机就会继续开门;这样一直进行下去,你可能需要等待几分钟,最终没人要上公交了,才会关门,然后发车。

let debounce = function (action, delay) {
    let timer = null;

    return function () {
        clearTimeout(timer);
        timer = setTimeout(() => {
            action.apply(this, arguments);
        }, delay);
    };
};

// example
function operationFn() {
    console.log("debounce---");
}

window.onclick = debounce(operationFn, 500);

节流(Throttling)

假设你正在坐公交,当公交到站后接到人准备启动车之前发现还有乘客要乘车,这时公交司机会按下开门开关,然后让乘客上公交;
但是,这个公交司机是没耐心的人,司机最多只会在这个站台停留一分钟;在这一分钟内,司机会开门让乘客进来,但是过了一分钟之后,司机就会关门,然后发车。

let throttle = function (action, delay) {
    let statTime = 0;

    return function () {
        let currTime = +new Date();
        // '+'的目的是通过隐式类型转换将该数据类型转换为Number类型,若转换失败,则返回NaN;
        if (currTime - statTime > delay) {
            action.apply(this, arguments);
            statTime = currTime;
        }
    };
};

// example
function operationFn() {
    console.log("throttle---");
}

window.onclick = throttle(operationFn, 1000);
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。