Use setTimeout to periodically call AJAX autocomplete?

I would like to use the setTimeout function, so that Ajax calls make no more than one second.

Here is what I have. This is clearly wrong, but I'm not sure how the setTimeout function works.

function autoComplete(q, succ)
{

    setTimeout(

    if(q != "") {
        $.ajax({type:"GET",
            url: "php/search.php",
            data: "q="+q,
            success: succ
        });
    }

    , 1000);
}

I think I should use clearTimeout, so if another call is made, it will reset the timer and wait another 1 second, but when I tried to implement this, it stopped the function.

+3
source share
1 answer

Pass the function ... :)

Using an anonymous function may be as follows:

var timeoutId
function autoComplete(q, succ)
{
    if (q) {
        // stop previous timeouts
        clearTimeout(timeoutId)
        timeoutId = setTimeout(function () {
            $.ajax({type:"GET",
                url: "php/search.php",
                data: "q="+q,
                success: succ
            });
         }, 1000);
    }
}

. q . , . , success - - . " q" q setTimeout .

var timeoutId
var counter = 0
function autoComplete(q, succ)
{
    if (q) {
        // Increment counter to maintain separate versions
        counter++
        var thisCounter = counter
        clearTimeout(timeoutId)
        timeoutId = setTimeout(function () {
            $.ajax({type:"GET",
                url: "php/search.php",
                data: "q="+q,
                success: function () {
                    // Only call success if this is the "latest"
                    if (counter == thisCounter) {
                       succ.apply(this, arguments)
                    }
                },
            });
         }, 1000);
    }
}

, ...

getQ ...

var timeoutId
var counter = 0
function autoComplete(getQ, succ)
{
    counter++
    var thisCounter = counter
    clearTimeout(timeoutId)
    timeoutId = setTimeout(function () {
        var q = getQ() // get the q ... NOW
        if (q) {
            $.ajax({type:"GET",
                url: "php/search.php",
                data: "q="+q,
                success: function () {
                    if (counter == thisCounter) {
                       succ.apply(this, arguments)
                    }
                },
            });
         }
     }, 1000);
}

// example usage
autoComplete(function () { return $(elm).val() }, successCallback)

.


, , , , ( , "" , ). AJAX , "-", .

+17

All Articles