Archive

Posts Tagged ‘Ajax’

Onkeyup delay in JavaScript

18 September 2009 3 comments

In a recent post I used a little script to delay the onkeyup event for a set amount of milliseconds after the key was released.  That way a callback will not be made for every key that gets released, but only once the user stopped typing.  That post was brought up many times by a search for this specific function, so I decided to extract it into its own post.

For this post I will only show an alert message to keep it to the bare minimum.

First we need to add this to our page, preferably in the <head> section.  Have a look here if you are not familiar with XHTML compliant JavaScript, it’s a short and straight to the point post.

<script language="javascript" type="text/javascript">
    //<![CDATA[
    function delayTimer() {
        var timer;
        return function(fun, time) {
            clearTimeout(timer);
            timer = setTimeout(fun, time);
        };
    }
    var delayFunction = delayTimer();

    function showMessage() {
        alert('Delay expired!');
    }
    //]]>
</script>

This is just a timer which restarts itself every time the onkeyup event triggers.  Once it runs out it will execute the function that you specify later.

<input id="txtDelay" type="text" onkeyup="delayFunction(showMessage, 500);" />

This is our input box which uses the onkeyup delay.  We use our delegate that we created and pass in two parameters, the first is the function to call and the second is the delay before doing so.  In this case it will wait 500ms before calling the showMessage function.

That is all you need to get a delay for an event in JavaScript.

NOTE: This does NOT work when pasting text in using the mouse.  Disable right-click on the input box if you rely on this function to execute.

Hope this is clear.  Comment if there is anything unclear or if you have a better way for me to do things.

Update – Passing in a parameter to the function as requested by a comment

<script language="javascript" type="text/javascript">
    //<![CDATA[
    function delayTimer() {
        var timer;
        return function (fun, time) {
            clearTimeout(timer);
            timer = setTimeout(fun, time);
        };
    }

    var delayFunction = delayTimer();

    // Takes parameters to display
    function showMessage(message, sender) {
        alert(message + " - " + $(sender).val());
    }
    //]]>
</script>
<!-- Now passing in a function with parameters -->
<input id="txtDelay" type="text" onkeyup="delayFunction(function() { showMessage('Display this string!', $('#txtDelay')); }, 500);" />

Note that passing in ‘this’ to the function in the onclick event does not send the input through.

Advertisement