would like help understanding javascript throttle function

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!

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")

1

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.

0

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật