Pregunta de entrevista de Google

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.

Respuestas de entrevistas

Anónimo

15 ago 2014

/* 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));

1

Anónimo

26 ene 2016

// Can't we just add a flag on the throttled function itself? function fn() { console.log('run at', new Date().getTime()); } function throttle(fn, delay) { if (!fn.lastRun || new Date().getTime() - fn.lastRun > delay) { fn.lastRun = new Date().getTime(); return fn(); } else console.log("wait"); } document.addEventListener("scroll", throttle.bind(null, fn, delay));

1