Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I wait until the user has finished writing down in a text input to call a function?

Tags:

I'm designing a web site and I would like to be able to call a function 1 second after the last user input. I tried using onKeyUp, but it waited 1 second after the first keystroke.

Does anyone know how would this be possible?

like image 654
Gab Royer Avatar asked Jun 26 '09 03:06

Gab Royer


People also ask

How do you trigger an event in input text after quitting typing writing react native?

$('input#username'). keypress(function() { var _this = $(this); // copy of this object for further usage setTimeout(function() { $. post('/ajax/fetch', { type: 'username', value: _this. val() }, function(data) { if(!

How do I prevent user input in a text box?

The disabled attribute can be set to keep a user from using the <input> element until some other condition has been met (like selecting a checkbox, etc.). Then, a JavaScript could remove the disabled value, and make the <input> element usable. Tip: Disabled <input> elements in a form will not be submitted!


2 Answers

Another similar approach, without globals:

var typewatch = function(){     var timer = 0;     return function(callback, ms){         clearTimeout (timer);         timer = setTimeout(callback, ms);     }   }();     

...

<input type="text" onKeyUp="typewatch(function(){alert('Time elapsed!');}, 1000 );" /> 

You can this snippet here.

like image 107
Christian C. Salvadó Avatar answered Oct 22 '22 17:10

Christian C. Salvadó


You can use a keyDown (or keyUp) event that sets a function to run in 1 second and if the user types another key within that second, you can clear the timeout and set a new one.

E.g.

var t;      function keyDown() {   if ( t )   {     clearTimeout( t );     t = setTimeout( myCallback, 1000 );   }   else   {     t = setTimeout( myCallback, 1000 );   } }  function myCallback() {    alert("It's been 1 second since you typed something"); } 
like image 35
jimr Avatar answered Oct 22 '22 18:10

jimr