Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call a function after a person stops typing?

I have an input on an HTML page where a person will type something and what I'm wanting is for a function to be called every time they stop typing. I know about the onkeypress event, but that is called every time a character is typed. Here's an example of what I would like:

  1. Person types "this is a test" into the input
  2. After the person stops typing, function foo() should be called
  3. Person types something else into the input
  4. After the person stops typing, function foo() should be called
  5. Repeat....

Is this possible?

Thanks a lot!

like image 241
Nate Avatar asked Jun 23 '12 20:06

Nate


1 Answers

Listen to onkeyupevent. There start a timeout (you have to define "stop" as some time amount, otherwise it will be called at every keyup), and in the timeout execute your function.

If onkeydown is called while your timer is running, stop it.

Something like...

var timer;

function onKeyUpHandler(e){
    timer = setTimeout("foo()", 500)    
}

function onKeyDownHandler(e) {
    clearTimeout(timer);
}

How this code exactly looks depends where and how you are using it... just to show the way to do it.

like image 146
User Avatar answered Oct 05 '22 23:10

User