views:

40

answers:

1

Does jQuery have any tools I can use for request-throttling? Something similar to how auto complete works.

More specifically this is the kind of thing I'm trying to do:

    **Customer entry:**
    First Name: J
    Last Name:  Smi

    **Search results:**
    Joe Shmoe     -edit button-
    John Smith    -edit button-
    Jane Smith    -edit button-
    Joe Smithers  -edit button-

When a user types a anything in either of the boxes, I'd like to formulate the request myself, and then jQuery can decide when and if to send the request, and then I would provide the code for handling the response.

A: 

Below is the code I ended up writing for throttling requests.

Initialization:

var global = {};
global.searchThrottle = Object.create(requestThrottle);

Usage:

this.searchThrottle.add(function(){
         //Do some search or whatever you want to throttle 
 });

Source code:

// runs only the most recent function added in the last 400 milliseconds, others are 
// discarded
var requestThrottle = {};

// Data
requestThrottle.delay = 400; // delay in miliseconds

requestThrottle.add = function(newRequest){
 this.nextRequest = newRequest;
 if( !this.pending ){
  this.pending = true;
  var that = this;
  setTimeout( function(){that.doRequest();}, this.delay);
 }
}

requestThrottle.doRequest = function(){
 var toDoRequest = this.nextRequest;
 this.nextRequest = null;
 this.pending = false;
 toDoRequest();
}

Object.create() source code (taken from "Javascript: The Good Parts"):

if( typeof Object.create !== 'function'){
 Object.create = function(o){
  var F = function(){};
  F.prototype = o;
  return new F();
 };
}
DutrowLLC
The setTimeout() method actually does take a function reference as the first parameter. You can do: '''function foo() {}; setTimeout(foo, 5000)'''. Since the deferred execution is, by default, in the window scope, object instance methods require addition currying (Jquery has currying plugins; Prototype has a built-in Function.curry)
johnvey
Yeah, you're right, I changed the code above. I'm not sure why every example I found online sends it a string as the first parameter.
DutrowLLC