And the throttle to achieve image stabilization in code

Shake

The concept: a callback to be triggered in the event n seconds, and then, if this has been triggered in n seconds, then re-timing.

Example: If someone into the elevator, that elevator will start after 10 seconds, then if someone into the elevator, and we have to wait 10 seconds before departure.

Ideas: closure by maintaining a variable, if this variable represents the timing has begun, before the start time if you have emptied the timer to restart timing.

function debounce(fn, time) {
  let timer = null;
  return function () {
    let context = this
    let args = arguments
    if (timer) {
      clearTimeout(timer);
      timer = null;
    }
    timer = setTimeout(function () {
      fn.apply(context, args)
    }, time)
  }
}
window.onscroll = debounce(function(){
  console.log('触发:'+ new Date().getTime());
},1000)

Throttling

The concept: a specified unit of time, within this unit time, only one trigger event callback execution, if an event is triggered in the same unit of time several times, only once can take effect.

Example: cooldown in the game, no matter how many times you press, the skills can only be triggered again after cooling good

Ideas: closure by maintaining a variable that is allowed to perform functions on behalf of, and if allowed to perform the function of that variable is not allowed to modify, and use a timer to recover the variable after a specified time.

function throttle(fn, time) {
  let canRun = true;
  return function () {
    if(canRun){
      fn.apply(this, arguments)
      canRun = false
      setTimeout(function () {
        canRun = true
      }, time)
    }
  }
}
window.onscroll = throttle(function(){
  console.log('触发:'+ new Date().getTime());
},1000)

 

Guess you like

Origin www.cnblogs.com/wtsx-2019/p/12615038.html