Asked me to write a throttle function in javascript. Well, essentially...he wanted me to write a function that would call another function, but not if it had been called within a certain set time, which is essentially what a throttle function is. I completely flailed, but it's a useful function to have...probably why they put it in the underscore library which is what I based this answer on.
Anónimo
/* var handle = setTimeout[myFunction, 5000); // Do this before it runs, and it'll never run clearTimeout(handle); */ // async(queue calls) or sync(and throw calls away while executing) var lastTime = new Date().getTime(); function foo() { var newTime = new Date().getTime(); var gap = newTime - lastTime; console.log('foo called, gap:' + gap); lastTime = newTime; } //Calls it immediately the first time and throttles it on subsequent calls //Non-queueing so calls during throttle period are ignored throttleFunction = function(func, wait) { var args, result; var timeout = null; //timeout call that acts as a flag var previous = 0; return function() { var now = new Date().getTime(); var remaining = wait - (now - previous); //how much time is left on wait args = arguments; //just pass along the args if (remaining <= 0) { clearTimeout(timeout); //reset Timeout function call timeout = null; //reset timeout variable previous = now; //reset time so we know when the last time function was called result = func.apply(this, args); args = null; //reset args } return result; }; }; document.addEventListener("scroll", throttleFunction(foo, 2000));