I have a fiddle and also same code below.
I want to achieve this --> user enters a (usually) 4-digit number, and when they are done, I want to run an AJAX call.
I have been trying to figure it out but so far it is not working.
var delay = (function() {
var timer = 0;
return function(callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();
$('order').keyup(function(e) {
delay(function() {
if (e.which >= 48 && e.which <= 57) {
console.log("INSIDE");
$.ajax({
type: "POST",
dataType: "json",
url: "/echo/json/",
data: 'order=' + $(this).val(),
cache: false,
success: function(json) {
$('#ref_job').empty();
$.each(json, function(i, value) {
$('#ref_job').append($('<option>').text(value).attr('value', value));
});
}
});
}
}, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="text" id="order" />
debouncefunctions that might be helpful for this. Essentially you call the debounced function on every keystroke, and then your wrapped function will only be called after a break of 1000ms or whatever you set.