函数节流、函数防抖

防抖:

  适用于input输入框格式验证、联系词等。待用户停止输入一段时间再发生请求,避免频繁请求。

  实现细节:debounce返回一个function,关键点在于clearTimeout,如果用户不停输入,就会一直执行clearTimeout,导致fn无法执行。只有用户停止x时间后,才会开始执行fn。

<input type="text" id="ipt">
let debounce = (fn, time) => {
    let timeout;

    return function (e) {
        let context = this,
            args = arguments;
        clearTimeout(timeout);
        timeout = setTimeout(() => {
            fn.apply(context, arguments);
        }, (time || 200));
    }
};

document.getElementById('ipt').addEventListener('input', debounce((e) => {
    console.log(e.target.value);
}, 300));

 

 

节流:节流不会像防抖那样,等用户行为停止x时间后执行,而是间隔x时间执行一次。

  适用于比input、keyup更加频繁的操作,比如mousemove、scroll、resize、touchmove

  实现细节:保存上次执行的时间点和定时器

<div id="rectangle"></div>
let throttle = (fn, time) => {
    let start = +new Date(),
        timeout;
    time = time || 200;

    return function () {
        let context = this,
            args = arguments,
            now = +new Date();
        clearTimeout(timeout);
        if (now - start >= time) {
            console.log(1111);
            fn.apply(context, arguments);
            start = now;
        } else {
       //让方法在脱离事件后也能执行一次 timeout
= setTimeout(() => { console.log(2222); fn.apply(context, arguments); }, time); } } }; document.getElementById('rectangle').addEventListener('mousemove', throttle((e) => { console.log(e.pageX, e.pageY); }, 1000));

 

posted @ 2018-12-14 17:47  tracy-ling  阅读(152)  评论(0编辑  收藏  举报