Anti-shake (JS event is triggered multiple times, only executed once)

Application scenario: Input input information for search, if every type of character request background interface, to the background pressure is too big, so do a good job of shaking, that is, let the program only execute the last event. To solve this problem, two solutions were explored:

  • Scheme 1: closure anti-shake

I have seen the case of using global variables for shock prevention before, but I think it is more perfect to use closure modularization, so that the code of the business layer can be clearly displayed, so that the code can be easily understood by multi-person collaborative teams.

<input type="text"> <script> let inp = document.querySelector('input'); inp.oninput = debounce(function() { console.log(this.value); }, 500) function debounce(fn,delay) {let t = null; return function(){ if (t! = null) {clearTimeout(t)} t = setTimeout(() => {// delay) } } </script>Copy the code
  • Scheme 2:

Use the Debounce method directly from the LoDash library at…

Throttling (controlling the frequency of execution of high frequency events)

Application scenario: the scroll wheel trigger events are frequent, and the delay can be triggered at low frequency

window.onscroll = throttle(function() {
      console.log('hello world');
    }, 500)
    function throttle (fn, delay) {
      let flag = true;
      return function () {
        if (flag) {
          setTimeout(() => {
            flag = true
        flag = false
Copy the code