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 5 years have passed since last update.

jQuery 連続でイベント発生したときに、イベント発生が落ち着いてから実行する

Last updated at Posted at 2020-05-26

概要

テキストボックスや、スライダーなどで、.on('input') などとinputイベントをとると、入力中、ドラッグ中に大量にイベント発火します。軽い処理であればリアルタイムに処理できて便利ですが、重い処理が多重発生するのは避けたい、ただ、操作時にすぐに実行したい、というときのスクリプトです。

CodePen

See the Pen Run after many events have fired by Tsuneaki Hasekura (@tsunet111) on CodePen.

イベントは連続で発火していますが、アラートがでるのは操作が終わった後です。

コード

1000msecごとにチェックのカウントを行い、カウントが2になったら実際の処理を実行します。

<h1>Run after many events have fired</h1>
<p>Event fire count : <span id="txt_count">0</span></p>
<p>
<input type="range" min="0" max="100" />
</p>
<p>
<input type="text" />
</p>
var num = 0;

var waitingTimer,waitCount;
var waitingFlg = false;
var waitMsec = 1000;
var waitNum = 2;

function wait_start(){
  waitCount = 0;
  waitingFlg = true;
  waitingTimer = setTimeout(wait_countup,waitMsec);
}

function wait_countup(){
  if(waitingTimer){
    clearTimeout(waitingTimer);
  }
  if(waitingFlg){
    waitCount++;
    if(waitCount==waitNum){
      waitingFlg = false;
      do_action();
    }else{
      waitingTimer = setTimeout(wait_countup,waitMsec);
    }
  }
}


function do_action(){
  alert('do action');
}

$(function(){
  $('input').on('input',function(){
    num++;
    $('#txt_count').html(num);
    wait_start();
  })
});

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?