简体   繁体   中英

jQuery Run AJAX only every x seconds

I'm trying to create a text input that uses ajax to get search results from the PHP script. Basically, at the moment the script sends each letter 1 by 1 to the PHP, which has to query the results from the database on each letter.

Instead, I would like it to be like if you type "Word" in 1 second, it just searches for entire "Word" instead of doing several searches for "W", "Wo", "Wor", "Word".

I tried to use window.SetTimetout for it, but that just makes it the search run 2 seconds late, but the letters are still sent 1 by 1.

$("#search").keyup(function(e) {
    var keyword = $("#search").val();
    window.setTimeout(function() {
        $.ajax({
            url: "GetItemList.php?search="+keyword,
            success: function(result) {
                $(".left").html(result);
            }
        });
    },2000);
});

Clear Timeout

var lastTimeout = null;
$("#search").keyup(function(e) {
    var keyword = $("#search").val();
    if (lastTimeout)
        clearTimeout(lastTimeout)
    lastTimeout = window.setTimeout(function() {
        $.ajax({
            url: "GetItemList.php?search="+keyword,
            success: function(result) {
                $(".left").html(result);
            }
        });
    },2000);
    });

You need to check if there is already a timeout active before you create a new one. Something like this:

var myTimeout = null;

$("#search").keyup(function(e) {
    var keyword = $("#search").val();

    if(myTimeout != null) {
        myTimeout = window.setTimeout(function() {
        $.ajax({
            url: "GetItemList.php?search="+keyword,
            success: function(result) {
                $(".left").html(result);
            myTimeout = null;
            }
        });
        },2000);
    }
});

This way, if you were to keep typing continuously for 10 seconds, you would end up with 4 or 5 requests total, one every 2 seconds or so.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM