Writing a throttle function

6/2/14

A throttle function can be useful in a few different scenarios, for example when you want to reduce the number of ajax calls being made from an app to your server. We'll be using autocomplete as an example.

Let's assume I have an autocomplete typeahead that makes ajax requests to do some type of server side search. For this case we'll assume we don't want to make a request for every single letter the user types in, but at a time we set to estimate that the user has stopped typing.

Our throttle function will take the function we want to throttle and a wait time, the function of which will be called after the wait. The simpliest form:

      
  function throttle (fn, wait) {
    var timeoutId;
    return function () {
      clearTimeout(timeoutId);
      timeoutId = setTimeout(fn, wait);
    };
  }
      
    

With context:

      
  function throttle (fn, context, wait) {
    var timeoutId;
    return function () {
      clearTimeout(timeoutId);
      timeoutId = setTimeout(function () {
        fn.call(context);
      }, wait);
    };
  }
      
    

With context and arguments:

      
  function throttle (fn, context, wait) {
    var timeoutId;
    return function () {
      var args = arguments;
      clearTimeout(timeoutId);
      timeoutId = setTimeout(function () {
        fn.apply(context, args);
      }, wait);
    };
  }
      
    

Lastly, what the throttle looks like in the context of autocomplete:

      
  // create our throttled handler
  var fetchResults = throttle(function (searchVal) {
    // ajax get for search value
  }, 300);

  // Using jquery and keyup on an input element
  $('#input').keyup(function (e) {
    var searchVal = $(this).val();

    if (searchval.length >= 3) {
      fetchResults(searchVal);
    }
  });
      
    

I hope you enjoyed this short tutorial, please comment with questions or feedback.

comments powered by Disqus