views:

309

answers:

7

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?

A: 

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.

ICodeForCoffee
onchange() does not occur when the user leaves the field, that would be onblur(). From the link you provided 'The onchange event occurs when the content of a field changes.'
karim79
Yes, but the field does not register a change at each key-stroke. If you press the enter key or, more commonly, the field loses focus then the change is picked up and the event fired.
AgileJon
+1  A: 

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).

Itay Moav
+1  A: 

I would go with the onblur event that occurs when an object loses focus. So it makes sure as soon as the user leaves the field that means he/she is done inputting their info.

TStamper
A: 

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!");
}
Gab Royer
Heh, that's nice. If someone is a really fast typer they might have to wait a few seconds to see the message though :-)
Dan F
+4  A: 

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");
}
jimr
Didn't know about clearTimeout! Thanks!
Gab Royer
+8  A: 

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
+1 for doing it without globals.
Egil Hansen
A: 

CMS.

This is fantastic.

var typewatch = function(){

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

Thanks, Kannan

kannan