You've got the right idea. You didn't see it in the docs for get
because it's not its job, it's a job for your code calling get
:
var timer = 0;
$('.form-control').keypress(function() {
clearTimeout(timer);
timer = setTimeout(handleKeypress, 200);
});
function handleKeypress() {
var o = $('#origin').val();
var d = $('#destination').val();
timer = 0;
$('#directions').html('Wait, please...');
$.get('/search', { origin: o, destination: d })
.done(function(data) {
$('#origin-info').html($('#origin').val());
$('#destination-info').html($('#destination').val());
$('#directions').html(data);
});
}
}
There, we start with a timer
variable with the value 0
(as 0
is an invalid timer handle clearTimeout
will silently ignore). When the user presses a key, we clear any previous timer and set a timer to call our function 200ms (a fifth of a second) later. If the user doesn't press another key, 200ms later we do our call; but if they do, the timer gets canceled (again), and we schedule a new one.
Side note: The above assumes you have only .form-control
, as appears to be the case in your code. But suppose you had several, and the information about what to do in the get
was stored on the .form-control
s? The above would be inappropriate, because typing in one of them, hitting tab to go to the next, and then typing in the next would prevent the first ever doing its work.
In that case, you'd store the timer handle on the element itself, using jQuery's data
:
$('.form-control').keypress(function() {
var $this = $(this),
timer = $this.data("keypress-timer");
clearTimeout(timer); // clearTimeout will ignore `undefined`, so this is fine the first time
timer = setTimeout(handleKeypress.bind(null, $this), 200);
});
function handleKeypress(control) {
var container = control.closest(".container");
var origin = container.find(".origin");
var destination = container.find(".destination");
var directions = container.find(".directions");
var o = origin.val();
var d = destination.val();
control.data("keypress-timer", 0);
directions.html('Wait, please...');
$.get('/search', { origin: o, destination: d })
.done(function(data) {
container.find('.origin-info').html(o);
container.find('.destination-info').html(d);
directions.html(data);
});
}
}
Note that that's just a hypothetical example, assuming these are in some kind of container and you can find the other relevant fields in that same container...