Sometimes you don’t want to execute functions as often as possible when events are triggered; When events such as resize, Scroll, and mousemove are triggered

A, stabilization,

Anti-shake means that the function is executed n seconds after the event is triggered. If it is triggered again within n seconds, the timer is reset

Non-immediate execution

function debounce(func, wait) {
  let timeout
  return function() {
    const context = this
    const args = [...arguments]
    if (timeout) clearTimeout(timeout)
    timeout = setTimeout(() => {
      func.call(context, args )
    })
  }
}
Copy the code

Executed immediately

function debounce(func, wait) { let timeout return function() { const context = this const args = [...arguments] if(timeout) clearTimeout(timeout) const callNow = ! timeout timeout = setTimeout(() => { timeout = null }, wait) if (callNow ) func.call(context, args) } }Copy the code

Second, the throttle

Throttling refers to the continuous firing of events, only once in a specified period of time

function throttle(func, wait) {
  let preTime = 0
  return function() {
    const nowTime = new Date().getTime()
    const context = this
    const args = [...arguments]
    if (nowTime - preTime > wait) {
      func.call(context, args)
      preTime = nowTime
    }
  }
}
Copy the code