I'm building a Drop-Down menu with AJAX, and I want to delay the user query for 3 seconds before actually submitting it.
So I tried something like this:
$("#search").keyup(function(){
clearTimeout(startcounting);
var startcounting = setTimeout(function() {
$.get( "mailing_search.php", { query: $("#searchitem").val() } ).done(function( data ) {
console.log("Query Submitted");
$("#searchbox").html(data);
});
},3000);
}
});
This doesn't work. it won't clear the timeout.
Lets say I input "samsung" it runs the query 7 times.
Any help?
Thanks in advance.
I think the problem is in the variable scope. You must declare startcounting
outside your function.
var startcounting;
$("#search").keyup(function(){
clearTimeout(startcounting);
startcounting = setTimeout(function() {
$.get( "mailing_search.php", { query: $("#searchitem").val() } ).done(function( data ) {
console.log("Query Submitted");
$("#searchbox").html(data);
});
},3000);
}
});