0
0

JavaScriptのdebounce実装方法

Posted at

どんな時にdebounceを使うか

高頻度で発火するイベントを制御したいとき、特定の時間間隔内に再度イベントが発火し、重複に関数を実行することを防ぐときに利用する一つ手法です

実装例

function debounce(fn, delay) {
    let timer_id;
    return function (...args) {
        clearTimeout(timer_id);
        let fn_this = this;
        timerId = setTimeout(function () {
          fn.apply(fn_this, args);
        }, delay);
    }
}

var tag_name = document.querySelector('tag_name');
tag_name.addEventListener('input|mousemove', debounce(function (e) {
    console.log('ユーザの操作:', e, this.value, '遅延させる');
}, 1000));


APIの利用例

const loadAd = debounce((query) => {
    fetch(`https://api.example.com?q=${query}`)
        .then(response => response.json())
        .then(data => {
            // 結果の表示や処理
        });
}, 1000);


document.querySelector('tag_name').addEventListener('click', (e) => {
    loadAd(e.target.value);
});
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