npmtest-mout (v0.0.1)

Code coverage report for node-npmtest-mout/node_modules/mout/function/throttle.js

Statements: 23.81% (5 / 21)      Branches: 0% (0 / 4)      Functions: 0% (0 / 4)      Lines: 23.81% (5 / 21)      Ignored: none     

All files » node-npmtest-mout/node_modules/mout/function/ » throttle.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 351       1     1         1                                   1        
var now = require('../time/now');
 
    /**
     */
    function throttle(fn, delay){
        var context, timeout, result, args,
            diff, prevCall = 0;
        function delayed(){
            prevCall = now();
            timeout = null;
            result = fn.apply(context, args);
        }
        function throttled(){
            context = this;
            args = arguments;
            diff = delay - (now() - prevCall);
            if (diff <= 0) {
                clearTimeout(timeout);
                delayed();
            } else if (! timeout) {
                timeout = setTimeout(delayed, diff);
            }
            return result;
        }
        throttled.cancel = function(){
            clearTimeout(timeout);
        };
        return throttled;
    }
 
    module.exports = throttle;