This function works (suspends the call) but the search value is not updated. If I enter "hello" the value passed to the function ($(this).val()) is "he". Is there a way to update it the key value so that it passes the whole search?.
$('#search').keyup(function () {
if ($(this).val().length > 1) {
var searchthis = $(this).val()
if (srun === 1 && stimer) {
if (stimer) {
window.clearTimeout(stimer)
}
} else {
srun = 1
var stimer = setTimeout(loadsearch(searchthis), 2000)
}
}
})
loadsearch() sets the var srun to 0;
Apparently, loadSearch is only called once when srun is not set. You should organize your code like this
//put timer outside
var stimer;
$('#search').keyup(function(e) {
if ($(this).val().length <= 1) {
return;
}
var searchthis = $(this).val();
window.clearTimeout(stimer);
stimer = setTimeout(function() {
loadsearch(searchthis);
}, 2000);
});
setTimeout
expect 1st parameter to be a callable function, therefore setTimeout(function(){})
If you put setTimeout(loadsearch(searchthis))
it will execute the loadSearch function directly without waiting for 2s.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.