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?

Intro

JavaScriptはシングルスレッドです。そのため、画面に多くの処理が連続して表示される場合、画面が次第に遅くなり、ユーザーは画面が止まる不便さを経験することになります。一般的なDOMオブジェクトのイベントリスナーを実行する際、リサイズやインプットなどのイベントはわずかな状況でも継続的にリクエストを実行します。これを特別な対策なしで使用すると、画面に大きなパフォーマンスの問題が発生することがあります。

Debounceとは何ですか?

特定の時間内にイベントが発生しない場合にロジックを実行します。

Throttlingとは何ですか?

毎ミリ秒ごとに特定の時間間隔の後、最初のクリックだけを即座に実行します(特定の時間内のイベントは無視されます)。

Sample Code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Debounce & Throttling</title>
</head>
<body>
    <h2>Debouncing </h2>
    <input class="searchBar" />
    <h2>Throttling </h2>
    <input class="searchBar2" />
<script>
    //debouncing ブラウザの性能向上のため、単一スレッドであるためよく使われる部分を減らす。 0.3秒間、inputイベントが発生しない場合は実行
    var searchBar = document.querySelector('.searchBar');
    var timer;
    searchBar.addEventListener('input',e =>{
        if(timer){
            clearTimeout(timer);
        }
        timer = setTimeout(()=>console.log('ajax call...',e.target.value),300);
    });

    //throttling
    //-> 毎ミリ秒ごとに特定時間間隔後に最初のクリックだけを直ちに実行させる。 (特定時間の間のイベントは無視する。 そのため、API call が減る。)
    var throttling_timer;
    var searchBar2 = document.querySelector('.searchBar2');
    searchBar2.addEventListener('input',e=>{
        if(!throttling_timer){
            throttling_timer = setTimeout(()=>{
                throttling_timer = null;
                console.log('ajax call.....', e.target.value);
            },300);
        }//既存のスロットリングタイマーが存在すると、ロジックを実行しない。 なければ0.3秒以後ロジックを遂行=>周期的に1回遂行する。
    });    

</script>
</body>
</html>

Result Image

image.png

Summary

簡単な内容ですが、実際にフロントエンド開発をしながらとても役に立つ部分です。 特に、共通コンポーネントを作成する際に、パフォーマンスの問題を減らすために上記の技術を使用しました。

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?