开发者

How to hold a few milliseconds before making a keyup event ajax request in jQuery

开发者 https://www.devze.com 2023-02-03 14:08 出处:网络
I am making a small app using the Google Maps API. You can the type pin in a textbox and an AJAX call will be fired to get the coordinates from my database. I am invoking the action on the keyup event

I am making a small app using the Google Maps API. You can the type pin in a textbox and an AJAX call will be fired to get the coordinates from my database. I am invoking the action on the keyup event and after 2 characters are in the textbox. The problem is that I want the user to be able to type the whole thing before I start shooting AJAX calls. I have set Asynch to false otherwise the asynchronous call doesn't let me remove the markers from the map and bring开发者_JAVA技巧s in more markers before they are all gone.

    $('input[name="location"]').keyup(function(){
        if($(this).val().length > 1){
            $(this).css('background', '#fff url("/images/indicator.gif") no-repeat center right');
            deleteOverlays();
            $.ajax({
                dataType: "json",
                url: "locAjax.php",
                data: ({term : this.value}),
                async: false,
                type: "GET",
                success: function(data) {
                    setMarkers(map, data);
                }
            });
            $(this).css('background', '#fff');
        }
    });

Can I use some sort of time out or something before the call to give the user time enough to write the whole thing. or at least half of it.

Please let me know.

Thanks a lot.


var timer;

$('input[name="location"]').keyup(function(){
    clearTimeout(timer);
    timer = setTimeout(function(){
    if($(this).val().length > 1){
        $(this).css('background', '#fff url("/images/indicator.gif") no-repeat center right');
        deleteOverlays();
        $.ajax({
            dataType: "json",
            url: "locAjax.php",
            data: ({term : this.value}),
            async: false,
            type: "GET",
            success: function(data) {
                setMarkers(map, data);
            }
        });
        $(this).css('background', '#fff');
    }
    }, 5000 ); // <--- do ajax call after 5 seconds of the last keyup character...
});


Its quite simple, you need to use setTimeout and clearTimeout. For example,

var timerId = null;
$('input[name="location"]').keyup(function(){
   if (timerId) {
      clearTimeout(timerId);
   }
   timerId = setTimeout(makeServiceCall, 20); // wait for 20 millisecond.
});

Here makeServiceCall will be the function that will have code outlined by you to make the service call. This function should also reset timerId to null. So whenever key is pressed, we will set the timer to fire service call, if key is pressed before time out occurs then we will reset previous timer and set a fresh one.

0

精彩评论

暂无评论...
验证码 换一张
取 消