防抖和节流笔记二

节流

原理:持续触发事件  每隔一段时间 只执行一次

//第一次会执行  最后一次不会被触发
// function throttle(func,wait){
//   let context,args
//   let old = 0
//   return function (){
//     // 执行这个函数时  获取当前时间戳
//    context = this
//    args = arguments
//     let now = new Date().valueOf()
//      if(now - old > wait){

//        //立即执行
//        func.apply(context,args)
//        old = now
//      }

//   }

// }

// 第一次不hi触发  最后一次触发

// 用定时器
function throttle(func,wait){
  let context,args,timeout

  return function (){
    // 执行这个函数时  获取当前时间戳
   context = this
   args = arguments
   if(!timeout){
    timeout =   setTimeout(()=>{
      timeout = null
       func.apply(context,args)
     },wait)
   }
 

  }

}


let count  = 0
let container = document.querySelector('#container')

function doSomeThing(e){
console.log(e)
container.innerHTML = count++

}
// let doSome = (doSomeThing,20000)
container.onmousemove = throttle(doSomeThing,2000)
原文地址:https://www.cnblogs.com/zfdbk/p/12981684.html