[JS] Throttle

簡單的版本:

let timeoutId;

btn.addEventListener('click', function (e) {
  if (!timeoutId) {
    console.log(new Date()); // 要執行的動作

    timeoutId = setTimeout(() => {
      timeoutId = null; // reset
    }, 1000);
  }
});

Demo
https://www.yuantw.com/demo/js-throttle-1/

———

Function 版:

function throttle(fn, delay = 1000) {
  let timeoutId;

  return function () {
    let context = this;
    let args = arguments;

    if (!timeoutId) {
      fn.apply(context, args);

      timeoutId = setTimeout(() => {
        timeoutId = null;
      }, delay);
    }
  };
}

function show(e) {
  console.log(`${e.target.dataset.text} --`, new Date());
}

Demo
https://www.yuantw.com/demo/js-throttle-2/

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

返回頂端