2627. Debounce

2627. Debounce

Debounce function :

A debounce function is a way to ensure that a function doesn't get called too often. It's often used in situations where you have an event that triggers frequently, like a button click or a scroll event on a web page.

  1. 給定一個時間 t 秒。

  2. 只要在 t 秒內呼叫 function 的話,先清除上一次設定的計時器,接著設置新的計時器。

  3. 而該 function 只會在最後一次設置的計時器到達 t 秒後才會真正被執行。

/**
 * @param {Function} fn
 * @param {number} t milliseconds
 * @return {Function}
 */

var debounce = function (fn, t) {
    let timer;
    return function (...args) {
        if (timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(() => {
            fn(...args);
        }, t);
    };
};