Image stabilization

Anti-shake: Use setTimeOut to trigger multiple times within a certain period => one time

// The anti-shock function debounce
function debounce(func, wait) {
  let timer = null;

  // Return the debouce result as a function
  return function() {
    let context = this;  // Change this inside the function
    let args = arguments; // event points to a problem
    if(timer) {
      clearTimeout(timer)
    }
    timer =  setTimeout(() = > {
      func.apply(context, args);
    }, wait)
    
  }
}
Copy the code

So how do I write that?

// Write the basic structure to return a function and use a timer
// Resolve this pointing and event issues
function debounce(func, wait){
    let timer = null
    return function(){
        let context = this;
        let args = arguments;
        if(timer) clearTimeout(timer)
        timer = setTimeout(() = > {
            func.apply(context, args);
        }, wait)
    }
}
Copy the code

The throttle

The concept of throttling is to turn multiple executions into periodic executions

// throttling function
function throttle(func, wait) {
  let begin = 0;
  return function() {
    let context = this;
    let args = arguments;
    let cur = new Date().getTime(); // Milliseconds timestamp
    if(cur - begin > wait){
      func.apply(context, arguments) begin = cur; }}}Copy the code