0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

jsイベント間引き - ES2015以降 - (throttle+debounce)

Posted at

環境

  • IEを考慮しないモダンブラウザ
  • webpack などビルドを使用しないシンプルなプロジェクト
  • VS Code で構文チェックを有効にしても認識できる状態

ライブラリを使うほどでないが、 throttle だけは使用したいので参考サイトを基に構文チェックで認識されるように修正

結論

//@ts-check

class Sample {

    /** 間引き処理 */
    throttle = (() => {
        let time = Date.now();
        let lag = 0;
        let debounceTimer = 0;
        let debounceDelay = 16;

        /**
         * 間引き (throttle+debounce)
         * @param {()=>void} callback 間引き処理
         * @param {number} interval 間引き間隔 (default: 200ミリ秒)
         */
        const func = (/** @type{()=>void}*/ callback, interval = 200) => {
            lag = time + interval - Date.now();
            if (lag < 0) {
                callback();
                time = Date.now();
            } else {
                clearTimeout(debounceTimer);
                debounceTimer = setTimeout(() => {
                    callback();
                }, interval - lag + debounceDelay);
            }
        };

        return func;
    })();
}

参考元

  1. https://qiita.com/akuden/items/5a24b0bd4b02b6756730
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?