views:

406

answers:

4

I have a textbox. I want to call a ajax callback function with some 2 second delay on every keyup.

How to implement this?

A: 

Using jQuery, but feel free to substitute your own JS library of choice:

var currentTimer = null;
input.bind('keyup', function () {
    if (!currentTimer) {
        currentTimer = true;
        setTimeout(function() {
            if (currentTimer) {
                currentTimer = null;

                // Do ajax call here
            }
        }, 2000);
    }
});
Augustus
A: 

I'm using jQuery here but you should get the point:

function callAjax() {
    timer = null;

    // handle all your ajax here
}

var timer = null;

$('input').keyup(function () {
    // this will prevent you from reseting the timer if another key is pressed
    if (timer === null) {
        timer = setTimeout(callAjax, 2000);
    }
});
RaYell
A: 

If you're using jQuery, you can use the excellent delayedObserver plugin.

Philippe Leybaert
A: 

2 second after last key press or every key press?

<input type="text" id="txtBox" value="" width="200px"/>
<input type="text" id="txt" width="200px"/>

<script type="text/javascript">
    $(document).ready(function(){
    $("#txtBox").keyup(function(){
        setTimeout(function(){
            $("#txt").val($("#txtBox").val());//Here call ajax code
        },2000);
      });
    });
</script>
Hi mate, I could do with this code. For me, when I run the code, it will wait 2 seconds regardless of whats being typed then run. Can you mod it so it re-sets the timer if another key is pressed?
Pace