Hi, 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?
Hi, 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?
You can use an onchange event which occurs when the user leaves the field and moves to the next field in the form. You can then add your wait code in there and fire that 1 second after the field changes.
There are no straight, 100% ways to do it. The simplest is to use the blur event of the input. (other ways might be to wait X seconds after the user finished typing).
Nevermind, I found a way to do it. I call a function on each onkeyup() which increment a counter and then wait 1 second. After the 1 second elapsed, it decrement the counter and check if it's equal to 0.
var keystrokes = 0;
function askAgain()
{
++keystrokes;
setTimeout(reveal, 1000);
}
function reveal()
{
--keystrokes;
if (keystrokes == 0)
alert("Watch out, there is a snake!");
}
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");
}
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.
CMS.
This is fantastic.
var typewatch = function(){ var timer = 0; return function(callback, ms){ clearTimeout (timer); timer = setTimeout(callback, ms); } }()
Thanks, Kannan