How to fire a jQuery function after the user stops typing?

Asked

Viewed 633 times

2

I have to do a search system that shows if an email is already registered in my database, but I do not know how to trigger a JS function after 3 seconds the user stops typing. I even tried with keyup but I couldn’t. Someone has some basis on how I can do this?

1 answer

2


You better use input instead of keyup, because the keyup will pick up any keystroke, even TAB, SHIFT or other. The input will call the function only when something is typed in the field.

You can do it this way:

var temporiza;
$("#email").on("input", function(){
   clearTimeout(temporiza);
   temporiza = setTimeout(function(){
      alert("Chama Ajax");
   }, 3000);
});

var temporiza;
$("#email").on("input", function(){
   clearTimeout(temporiza);
   temporiza = setTimeout(function(){
      alert("Chama Ajax");
   }, 3000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="email" id="email" placeholder="Digite o e-mail" />

  • I saw a problem kind of silly however it is essential for a good functioning, the timer must reset every time the key is pressed it seems to me that this way will not work like this

  • @Estudtephp Works this way: every time a character is inserted in the field, the timer Zera. If you think it best to put keyup, works also, will pick any key pressed.

  • worked perfectly here thanks :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.