underscore.js: _.throttle(function, wait)

前端 未结 5 1079
轮回少年
轮回少年 2021-02-19 13:21

According the underscore documentation:

throttle_.throttle(function, wait)
Creates and returns a new, throttled version of the pa

5条回答
  •  北荒
    北荒 (楼主)
    2021-02-19 13:44

    I found this excellent jsfiddle that helped me:

    jsfiddle.net/max23_/2wn5ybdg/1 (updated by @max23_)

    In my case I needed throttle because a function (which was a server request) was being called about 500 times in 1 second, and was overloading the server. So I changed it so that the function could only be called max once per 3 seconds. So it doesn't matter how many times it's called, it'll only occur once per 3 seconds max.

    Something like this:

    var informationFromServer;
    var a = _.throttle(function(){
        informationFromServer = serverCallFunction();
    }, 3000);
    
    function getsCalledALot()
    {
        a();
    }
    
    function serverCallFunction()
    {
        var data = $.post....
        return data;
    }
    

提交回复
热议问题