节流函数 与防抖函数

2020-03-22  本文已影响0人  lessonSam

// 防抖 就是在事件触发后在一定时间只响应 一次 如果再时间内二次或多次触发 则以最后一次触发的世间为准
// 节流 连续发生的事件在 n 秒内只执行一次

    let num =1
    let content =document.getElementById('content');
    function count() {
      content.innerHTML=num++
    }
// content.onmousemove=count
// 输入完 过一秒执行    输入国
//     function debounce(fn,wait) {
//         let timeout =null
//         return function () {
//           if(timeout) clearTimeout(timeout)
//           timeout=setTimeout(function () {
//             fn.call(this,arguments)
//           },wait)
//         }
//     }
    // 输入完毕后 立即查询 过两秒后才能再次执行
    // function debounce(fn,wait){
    //   // 先定义一个变量
    //   let timeout;
    //   return function () {
    //     // 如果定时器 存在 就清空
    //     if(timeout) clearTimeout(timeout);
    //     // 保存定时器的状态值并取反,
    //     let callNow =!timeout;
    //     // 创建一个定时器 并释放 如果
    //     timeout =setTimeout(function () {
    //         timeout=null; //清除定时器 句柄
    //     },wait);
    //     // 如果 定时器存在我就不执行 如果定时器不存在我就立即执行
    //     if(callNow) fn.apply(this,arguments)
    //   }
    //
    // }

    // content.onmousemove=debounce(count,1000)
    //     节流函数 throttle
    function throttle(fn,awit) {
        let timeout =null
        return function () {
            if(!timeout){
              timeout=setTimeout(function () {
                timeout=null

                fn.apply(this,arguments)
              },awit)
            }
        }
    }
content.onmousemove=throttle(count,1000)
上一篇 下一篇

猜你喜欢

热点阅读