JQuery Delay between key features

I have some code that I am trying to integrate with the bing search API on my site with instant search results. I use the jquery keyup function to send data to the server side of the script, which then receives the bing search XML request and shows the results.

My concern is that I will make too many extra hits on my scripts. Can someone please take a look at this and tell me how can I put 1 second delay between keyboards as a timer? so will it update the results in just one second?

This is what I have created so far, but I do not know if this is correct.

<script type="text/javascript">
var delay = (function() {

    var timer = 0;

    return function(callback, ms) {

        clearTimeout(timer);

        timer = setTimeout(callback, ms);

    };

})();



function reloadsearch() {
    var searchterms = $('#q').val();
    if (searchterms.length >= 3) {
        delay(function() {
            var data = 'source=ajax&q=' + searchterms;
            $.ajax({
                type: "GET",
                url: "results/",
                data: data,
                success: function(html) {
                    if (html !== '') {
                        $("#search-results").html(html);
                        $("#search-results").fadeIn(500);
                    }
                }
            });
        }, 250);
    }

    else

    {
        $("#search-results").fadeOut(250);
    }
};



$('#q').keyup(function() {
    reloadsearch()
});

$(document).ready(function() {
    reloadsearch()
});

+3
source share
3 answers

, , .

http://jsbin.com/ebela4/8/edit

ajax, . , . . , "", .

, .

+5

-

    var delay = false;
$('#q').keyup(function() {

if(!delay){
    delay = true;
    reloadsearch().delay(1000);
    delay = false;
});

, ! Syntex .

, , :

$(document).ready(function(){

function reloadsearch() {
    var searchterms = $('#q').val();
    if (searchterms.length >= 3) {

            var data = 'source=ajax&q=' + searchterms;
            $.ajax({
                type: "GET",
                url: "results/",
                data: data,
                success: function(html) {
                    if (html !== '') {
                        $("#search-results").html(html);
                        $("#search-results").fadeIn(500);
                    }
                }
            });
       }

    else

    {
        $("#search-results").fadeOut(250);
    }
};

var delayOn = false;
$("#test").click(function(){
if(!delayOn){
delayOn = true;
reloadsearch().delay(2000).queue(function(){delayOn = false;$(this).dequeue();});
        }
                  });
                 });
+1

Here is an example similar to a Google search. It will not search until the user pauses text input.

http://jsfiddle.net/WNX5q/

+1
source

Source: https://habr.com/ru/post/1778356/


All Articles