Throttle JavaScript function calls, but with queuing (don't discard calls)

后端 未结 3 1867
醉梦人生
醉梦人生 2021-02-08 00:02

How can a function rate-limit its calls? The calls should not be discarded if too frequent, but rather be queued up and spaced out in time, X milliseconds apart. I\'ve looked at

3条回答
  •  伪装坚强ぢ
    2021-02-08 00:43

    Should be rather simple without a library:

    var stack = [], 
        timer = null;
    
    function process() {
        var item = stack.shift();
        // process
        if (stack.length === 0) {
            clearInterval(timer);
            timer = null;
        }
    }
    
    function queue(item) {
        stack.push(item);
        if (timer === null) {
            timer = setInterval(process, 500);
        }
    }
    

    http://jsfiddle.net/6TPed/4/

提交回复
热议问题