I have a page where search resuts are shown both in a grid and on a map (using KML generated on the fly, overlaid on an embedded Google map). I’ve wired this up to work as the user types; here’s the skeleton of my code, which works:
$(function() { // Wire up search textbox $('input.Search').bind('keyup', update); }); update = function(e) { // Get text from search box // Pass to web method and bind to concessions grid $.ajax({ ... success: function(msg) { displayResults(msg, filterParams); }, }); } displayResults = function(msg, filterParams) { // Databind results grid using jTemplates // Show results on map: Pass parameters to KML generator and overlay on map }
Depending on the search, there may be hundreds of results; and so the work that happens in displayResults is processor-intensive both on the server (querying the database, building and simplifying the KML on the fly) and on the client (databinding the results grid, overlaying big KML files on the map).
I like the immediacy of getting progressively narrower results as I type, but I’d like to minimize the number of times this refreshes. What’s the simplest way to introduce an N-second delay after the user stops typing, before running the update function?
Instead of calling
update()directly, call a wrapper that checks to see if there are any pending delayed updates:You should also probably add:
This will do an immediate update when the user leaves the field. But make sure you also add handling for the case where the user leaves the field while there’s a pending delayed update (cancel the delayed update first).