JSFiddle - React, Tailwind, and code Playground

by bittersweetryan

JavaScript

/**
write a function, throttle, that returns a function that run only once per n milliseconds.  

The function should accept 3 parameters: 
 * the function to call
 * a waite time (in millisecondss)
 * and an optional scope to apply to the new function.
**/

var lastTime;

function throttle(callback, waittime, scope) {    
    var curTime = 0
    , scp = scope || this;
    
    return function() {        
        var ltime
        , delay  = curTime - ltime;
        , lastInvoked;
                
        if (delay >= waittime) {
            lastInvoked = new Date().getMilliseconds();    
            callback.apply(scp, Array.prototype.slice.call(arguments));
        }
        else {               
            setTimeout(function() { throttle(callback, waittime, scope) }, delay);        
        }
        lastTime = new Date().getMilliseconds();
     };
  
}


var t_c = throttle( function( name ) { console.log( 'hello, ' + name ) }, 1500 );

t_c( 'ryan' );