//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 );
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.