防抖

by Boyanliuu

HTML

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>倒计时</title>
    </head>
    <body>
  <button class="input">
    Button
  </button>
    </body>

</html>

CSS

body{
  height:100vh;
  display:flex;
  justify-content:center;
  align-items:center;
}

.input{
  background:lightblue;
  padding:24px;
  border:0;
  outline:0;
  border-radius:10px;
  cursor:pointer;
}

JavaScript

const button  = document.querySelector('button');

function PayMoney(){
console.log('Paid!')
}


/* function debounce(func,delay){
  // 使用 closure 
  let timer;
  // 使用 高阶函数, high order function, 这样子 就只会在点击时候 
  // 才执行
  return function(){

      let context = this;
      // 清楚上一个定义的延时
      clearTimeout(timer);
      let args = arguments;
      timer = setTimeout(function(){
          //使用 apply 解决参数问题
          //保证this 指向正确
          func.apply(context,arguments);
      }, delay);
  }
} */


function debounce(func, wait, immediate) {

    var timeout;

    return function () {
        var context = this;
        var args = arguments;
        if (timeout) clearTimeout(timeout);
        if (immediate) {
            // 如果已经执行过,不再执行
            var callNow = !timeout;
            timeout = setTimeout(function(){
                timeout = null;
            }, wait)
            if (callNow) func.apply(context, args)
        }
        else {
            timeout = setTimeout(function(){
                func.apply(context, args)
            }, wait);
        }
    }
}


button.addEventListener('click',debounce(PayMoney,1000,true));