0

I'm using google maps API. I use a $.getJSON on .keyup() to geocode the address. This shows the location on the map for each type of the key. The problem is if you type too fast it freezes up. This is because the $.getJSON hits the Google DB too many times in too short a time. I was thinking of putting delay(); or something on the code. But, it doesn't seem to work. Here's the jQuery:

$('#create_loc_input').keyup(function() {
            var loc = $('#create_loc_input').val();
            $.getJSON('http://localhost/app/search/search.json.php?loc='+loc, function(data) {
                    lat = data.results[0].geometry.location.lat;
                    lng = data.results[0].geometry.location.lng;

                    $.post('app/create_page/func/create_page_messages.func.php', {
                                                         lat:lat,
                                                         lng:lng,
                                                         },
                    function(data) {
                        $('#create_latlng').html(data);
                        codeAddress();
                        });

                    });
            });

There's obviously a lot more to the code. But, in here, how could I limit the query to every 3 or so seconds. Kind of like a sudo keyup(). Limiting the $.getJSON to a max of one request per 3 seconds would be nice. Is that even possible? I tried delay() in various places. But, so far thats not doing the job.

Graham
  • 1,433
  • 3
  • 21
  • 34
  • possible duplicate of [delaying actions between keypress in jQuery](http://stackoverflow.com/questions/2410937/delaying-actions-between-keypress-in-jquery) – Jordan Running Nov 15 '11 at 05:08

1 Answers1

2

On keyup use setTimeout() to schedule the $.getJSON() call for three seconds' time, and then on subsequent keyups cancel any outstanding timeout and set another. That way the JSON request only happens three seconds after the last keystroke (and a minimum of three seconds after the previous request).

var timeoutID = null;
$('#create_loc_input').keyup(function() {
   if (timeoutID != null)
      clearTimeout(timeoutID);

   timeoutID = setTimeout(function() {
                             timeoutID = null;
                             // all of your other code here
                          }, 3000);
});
nnnnnn
  • 147,572
  • 30
  • 200
  • 241