Throttle 和 Debounce

节流函数和防抖函数

by Fan_90

HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Throttle 和 Debounce</title>
</head>
<body>
  <div>
    <label for="input1">正常 keyup监听</label>
    <input type="text" id="input1"> &nbsp;&nbsp;&nbsp;
    <span id="span1"></span>
  </div>
  <div>
    <label for="input2">Throttle keyup监听</label>
    <input type="text" id="input2">&nbsp;&nbsp;&nbsp;
    <span id="span2"></span>
  </div>
  <div>
    <label for="input3">Debounce keyup监听</label>
    <input type="text" id="input3">&nbsp;&nbsp;&nbsp;
    <span id="span3"></span>
    </div>
</body>
<script>
// 节流函数
const throttle = (func, limit) => {
  let inThrottle;
  return function () {
    if(!inThrottle) {
      func.apply(this, arguments)
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  }
}

// 防抖函数
const debounce = (func, wait) => {
  let timeout;
  return function () {
    let context = this, args = arguments;
    let later = function () {
      func.apply(context, args);
      timeout = null;
    }
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  }
}

const input1 = document.getElementById('input1');
const input2 = document.getElementById('input2');
const input3 = document.getElementById('input3');

const span1 = document.getElementById('span1');
const span2 = document.getElementById('span2');
const span3 = document.getElementById('span3');

input1.addEventListener('keyup', function (event) {
 span1.innerText = `${span1.innerText} ${event.target.value} ;`;
})

let throttleFunc = throttle( (value) => {
  span2.innerText = `${span2.innerText} ${value} ;`;
}, 1000)

let debounceFunc = debounce( (value) => {
  span3.innerText = `${span3.innerText} ${value} ;`;
}, 1000)

input2.addEventListener('keyup', function (event) {
  throttleFunc(event.target.value)
})

input3.addEventListener('keyup', function (event) {
 ...