Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

A user on Stack Overflow posted a question related to overriding a native JS function. The question is here and this is the code:

function throttle(fn, time) {
  var handle;

  var execute = function() {
    handle = null;
    fn.apply(this, arguments);
  };

  var throttled = function() {
    if(!handle) {
      handle = setTimeout(execute.bind(this), time);
    }
  };

  throttled.toString = function() {
    return fn.toString() + "\n// throttled to " + time + "ms";
  };

  return throttled;
}

var makeAjax = throttle(function(callback) {
  $.getJSON("/path", callback);
}, 500);

I have a pretty good handle (I think) on JavaScript, but there are some areas that remain very grey to me. I would like to know what is happening in this code?

I don't really understand what bind and apply are doing, or what the end result of this all would be. I've looked up bind and apply on Mozilla's JS documentation, but the "official" definition has done little to help me understand what they are doing in this context.

I appreciate your help!

share|improve this question
add comment

2 Answers 2

up vote 1 down vote accepted

I found it quite hard to read as well, context juggling code is in general hard to read, and therefore error-prone.

this in JavaScript often refer to the parent of the function, that is, when a function is stored as the field of an object like:

function fun(){
    return this
}
obj = {f:fun}

Calling obj.f() will return obj, simply calling fun() however will return the window element as the function is not called as a member, so the value of this depend on context. When making a wrapper like the one you show the context for this will invariably change, the bind and apply methods are made for dealing with situations like that. fun.bind(cont) will make a version of fun where this is always cont. fun.apply(cont,args) will run fun with this set to cont and the values in the array args as parameters.

The code in question demonstrate how convoluted these things get by failing to pass the given arguments to the function. The real parameters are passed to throttled, but the arguments array that is used come from execute, it is empty.

Using the bind function is unnecessary, this could just as well be stored in a simple variable.

Here is a fixed, and in my opinion easier to read, version, along with code that demonstrate the functionality:

function throttle(fn, time) {
    var handle;
    function throttled() {
        var args;
        var context;
        if(!handle) {
            args = arguments;
            context = this;
            handle = setTimeout(execute, time);
        }

        function execute() {
            handle = null;
            fn.apply(context, args);
        };
    };

    throttled.toString = function() {
        return fn.toString() + "\n// throttled to " + time + "ms";
    };

    return throttled;
}

obj = {
    toString:function(){
        return "obj's toString";
    }
    ,f:throttle(function(input){
        console.log(input+", "+this);
    },1000)
}
obj.f("input string 1")
obj.f("input string 2")
obj.f("input string 3")
obj.f("input string 4")
share|improve this answer
    
You're explanation of bind and apply completely makes sense. Thank you! –  jwatts1980 Jan 14 '13 at 16:04
add comment

It's quite simple really - the handle of a setTimeout call is used as a guard against multiple execution.

The throttled variable contains a function that is also the return value - makeAjax will contain that function. When it is executed, it will either

  1. Cause the execute function to be called after a delay, if handle has been cleared / not already set

  2. Return immediately otherwise.

This makes the name of the function apparent - it throttles the execution of the input function to after a certain time, and no more than once concurrently.

It uses bind to set the this context of the function stored in the execute variable.

The execute variable is a function wrapping the calling of the input function with the clearing of the handle, so that whenever the function stored in execute is called it allows further executions of the function. The function uses apply to execute the function with a specific context and arguments.

I hope that clears something up - I found it hard to put into words at all, and I'm not sure I managed it in a clear and concise way.

share|improve this answer
    
+1 for first response and helpful explanation. Thanks! –  jwatts1980 Jan 14 '13 at 16:04
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.