如何限制复选框选中和取消选中操作

How to throttle checkbox check & uncheck actions

我可以知道如何限制复选框选中和取消选中操作以防止用户单击复选框并过于频繁地更改选中和取消选中吗?如何使用throttle函数来控制check & uncheck动作?例如,即使用户点击 100 次,我们也最多每 2000 毫秒更改选中和取消选中。
参考:https://towardsdev.com/debouncing-and-throttling-in-javascript-8862efe2b563

const throttle = (func, limit) => {
  let inThrottle;
  return function() {
    if (!inThrottle) {
      func();
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  }
}
<input type = "checkbox" id = "checkbox1">
<label for="checkAll">Checkbox 1</label>

您可以使用 Date.now() 并测量毫秒数。

const c = document.getElementById("c");

const throttleMs = 500; // how much you'd like to throttle in milliseconds
let lastClick = Date.now();
c.addEventListener("change", e => {
  // check if last date - current date is less than 500ms
  if (Date.now() - lastClick < throttleMs) {
    c.checked = !c.checked; // e.preventDefault() doesn't work for checkboxes
  }
  lastClick = Date.now();
});
<input type="checkbox" id="c" />

您可以使用e.preventDefault()来控制check/uncheck动作。

const throttle = (func, limit) => {
  let inThrottle;
  
  return function(e) {
    if (inThrottle) {
      return e.preventDefault();  // Prevents check/uncheck of the input
    }
    
    func();
    inThrottle = true;
    setTimeout(() => inThrottle = false, limit);
  }
}

function clickHandler() {}

document.getElementById("checkbox1").addEventListener("click", throttle(clickHandler, 2000))
<input type = "checkbox" id = "checkbox1">
<label for="checkAll">Checkbox 1 (Can only be changed every 2s)</label>