2

I would like you show an alert message after the function keyup(). For this I use the following code:

$('#myInputingNumber').keyup(function() {
  alert ("Key Up")
})

This works good and the alert message shows after each keyup call. But this is not really good.

Is there any way to check, if the user has 2 seconds long no "keyup" and show only then the alert message?

Kunj
  • 1,980
  • 2
  • 22
  • 34
Trombone0904
  • 4,132
  • 8
  • 51
  • 104
  • Possible healping threads- [How to delay the .keyup() handler until the user stops typing?](https://stackoverflow.com/questions/1909441/how-to-delay-the-keyup-handler-until-the-user-stops-typing) And Search on google->`jQuery keyup with delay` – Alive to die - Anant Feb 05 '18 at 10:03
  • Possible duplicate of [Run javascript function when user finishes typing instead of on key up?](https://stackoverflow.com/questions/4220126/run-javascript-function-when-user-finishes-typing-instead-of-on-key-up) – empiric Feb 05 '18 at 10:04
  • Possible duplicate of [How to delay the .keyup() handler until the user stops typing?](https://stackoverflow.com/questions/1909441/how-to-delay-the-keyup-handler-until-the-user-stops-typing) – Andreas Feb 05 '18 at 10:14
  • Also, check out the concept of "debounce" – Martijn Feb 05 '18 at 10:51

2 Answers2

3

 let delay = (()=>{
      let timer = 0;
      return function(callback, ms){
        clearTimeout (timer);
        timer = setTimeout(callback, ms);
      };
    })();

    window.document.getElementById("myInputingNumber").addEventListener("keyup",function() {
        delay(function(){
          alert('Key Up');
        }, 2000 );
    });
<input type="text" id="myInputingNumber">
xale94
  • 424
  • 5
  • 12
0

You can try this one also.

var flag = false;
$(function(){
  $("#demoKeyup")
  .keydown(function(){
    flag = true;
    setTimeout(function(){
      if (flag == true) {
        alert("still key down");
        flag = false;
      }
    },2000);
  })
  .keyup(function(){
    flag = false;
  })

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<input type="text" id="demoKeyup">
Tonmoy Nandy
  • 371
  • 4
  • 9