JSFiddle - React, Tailwind, and code Playground

by bittersweetryan

JavaScript

//write a function called throttle that will return a new function that will only execute only once per n milliseconds specified

var throttle = function( fn, timeout, scope ){
  //this function should return a function that only run once per amount of milliseconds passed into the timeout variable.  The scope of the returned function should also be bound to the scope argument
    
    var lastTime;
    return function(){
        var currentTime =  Date.now();
        if( (currentTime - lastTime) > timeout || !lastTime){
            fn.call(scope);
            
            lastTime = currentTime;
        }
        
    };
    
    
    
};


console.time( 'throttled' );

//this function should output "Netflix" and "throttled ~1000ms" only once persecond

var toThrottle = function(){
  console.log( this );
  console.timeEnd( 'throttled' );
  console.time( 'throttled' );
};


var throttled = throttle( toThrottle, 1000, 'Netflix' );

var i = 0;

var toCallback = function(){
  i++;
  throttled();
  
  if( i < 100 ){
    to = setTimeout( toCallback, 200 );
  }
  
};

var to = setTimeout( toCallback, 200 );