Search code examples
javascriptonkeyuptimedelay

JavaScript onKeyUp time delay


I need some help with a JavaScript function that I call onKeyUp, it is a Ajax function but every time I write any character it calls the function and it slow the page performance and it check every time, it is an user check with the database.

I tried this:

 var timer;
 function chk_me(){

   clearTimeout(timer);
   timer=setTimeout(function validate(){...},1000);
}

But my validate function have a parameter so I am unable to pass it, I call the function like this:

<input type="text" name="usuario" id="usuario" class="required" onKeyUp="chk_me();" minlegth="4" value=/> 

Is it right? What should I do?

It is my first question and I hope that you all understand it

Thanks, Alberto

Thank you all, since I am new I cant do it in a different answer so I edited my question with the solution. I find this: http://bytes.com/topic/javascript/answers/451142-need-advice-acting-only-last-onkeyup-event-series and use the last answer method and add it some code, I leave you the code, like it say it isnt the best way but works so if you have some other way I will appreciate it and use it here it is:

var keyCount = 0;
var timeoutCount = 0;

function handleKeyUp() // keyup handler
{
keyCount++;
setTimeout("compareCounts()", 500);
}

function compareCounts()
{
var usuario = document.profileForm.usuario.value;
timeoutCount++;
if (keyCount == timeoutCount)
{
xajax_checaUsuario(usuario);
}
}

So I take the var in that way any suggestions to make it better?

Thanks


Solution

  • Don't pass validate directly to setTimeout, but rather call it from within an anonymous function:

    var timer;
    function chk_me(arg) {
        clearTimeout(timer);
        timer = setTimeout(function () {
            validate(arg);
        }, 1000);
    }