1

The HTML code: <input id="goTOxQuestion">
The js code:

$("#goTOxQuestion").keyup(function(){
    // send a XHR
})

If the input is 12345,it will send the XHR five times.
In fact, I only want the XHR be executed when I have completed the input. I mean,there is no input( no keydown event )in 500 milliseconds, rather then it loses faocus.
My incomplete solution:

var isOver = false;
$("#goTOxQuestion").keyup(function(){
    //...
    setTimeout(function(){
        if(isOver){
            //send a XHR
        }
    },500);
})
$("#goTOxQuestion").keydown(function(){
    isOver = false;
})
Salman A
  • 262,204
  • 82
  • 430
  • 521
ZhouMengkang
  • 193
  • 8

4 Answers4

1

Use setTimeout then:

$("#goTOxQuestion").keyup(function(){
    setTimeout(function(){
        // send a XHR
    }, 1000);
})
Jai
  • 74,255
  • 12
  • 74
  • 103
  • Here is a corresponding fiddle http://jsfiddle.net/m4ABn/8/ It works, but calls alert a couple of times in the end :S – Daniel Fath Jan 17 '14 at 08:34
1

The change event seems like a good fit for your needs :

$("#goTOxQuestion").change(function(){
    // send a XHR
})

It will be triggered when the input looses focus and the input value was actually modified.

LeGEC
  • 46,477
  • 5
  • 57
  • 104
1

You can use a combination of setTimeout and clearTimeout like this:

var hTimeout;
$("#goTOxQuestion").keyup(function () {
    if (hTimeout) {
        clearTimeout(hTimeout);
    }
    hTimeout = setTimeout(function () {
        // ajax code here
    }, 500);
});

Demo here

Note that the order in which AJAX requests complete is not guaranteed and you will end up with "race conditions".


Regarding your comment, here is a solution from the top of my mind:

// initialize global counter
var xhrCount = 0;
// increment counter when you create an XHR
xhrCount++;
// pass the current value of this
// variable to the success function
// http://stackoverflow.com/q/1552941/87015
$.ajax("/url/", (function (myStamp) {
    console.log("creating success callback #" + myStamp);
    return function () {
        if (myStamp === xhrCount) {
            console.log("firing success handler");
        } else {
            console.log("suppressing success handler");
        }
    }
})(xhrCount));
Salman A
  • 262,204
  • 82
  • 430
  • 521
  • Note that the order in which AJAX requests complete is not guaranteed....I need the last request.thanks – ZhouMengkang Jan 17 '14 at 08:49
  • Detecting if the request was the last one could be a pita. You can try (i) declaring a global counter (ii) increment the counter when AJAX is created (iii) in the success function, compare the current request's number with global counter. – Salman A Jan 17 '14 at 09:37
0
$(document).on('blur',"#goTOxQuestion",function(){
    // send a XHR
});
A.T.
  • 24,694
  • 8
  • 47
  • 65