1function throttle (callback, limit) {
2 var wait = false; // Initially, we're not waiting
3 return function () { // We return a throttled function
4 if (!wait) { // If we're not waiting
5 callback.call(); // Execute users function
6 wait = true; // Prevent future invocations
7 setTimeout(function () { // After a period of time
8 wait = false; // And allow future invocations
9 }, limit);
10 }
11 }
12}
13// Usage Example:
14// On scroll, allow function to run at most 1 time per 100ms
15window.addEventListener("scroll", throttle(function(){
16 /*stuff to be throttled*/
17}, 100));
1function throttle (callback, limit) {
2 var wait = false; // initial step when we are nit waiting
3 return function () { // returnimg a throttled function
4 if (!wait) { // while not waiting
5 callback.call(); // Executing users function
6 wait = true; // Preventing future invocations
7 setTimeout(function () { // after certain interval of time
8 wait = false; // allow future invocations
9 }, limit);
10 }
11 }
12}
13// Usage Example:
14// On scroll, allow function to run at most 1 time per 100ms
15window.addEventListener("scroll", throttle(function(){
16 /*stuff to be throttled*/
17}, 100));