时间: 2020-09-6|tag:32次围观|0 条评论

防抖(Debouncing)

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

let debounce = function (action, delay) {    let timer = null;    return function () {        clearTimeout(timer);        timer = setTimeout(function () {            action.apply(this, arguments);        }, delay);    };};// examplefunction 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;        }    };};// examplefunction operationFn() {    console.log("throttle---");}window.onclick = throttle(operationFn, 1000);

文章转载于:https://www.jianshu.com/p/7890fd811f6e

原著是一个有趣的人,若有侵权,请通知删除

本博客所有文章如无特别注明均为原创。
复制或转载请以超链接形式注明转自起风了,原文地址《JavaScript防抖(Debouncing)和节流(Throttling)
   

还没有人抢沙发呢~