Created
February 28, 2013 21:44
-
-
Save dwelch2344/5060372 to your computer and use it in GitHub Desktop.
Throttling function, abstracted from Underscore
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var throttle = function (func, wait) { | |
| var context, args, timeout, result; | |
| var previous = 0; | |
| var later = function() { | |
| previous = new Date(); | |
| timeout = null; | |
| result = func.apply(context, args); | |
| }; | |
| return function() { | |
| var now = new Date(); | |
| var remaining = wait - (now - previous); | |
| context = this; | |
| args = arguments; | |
| if (remaining <= 0) { | |
| clearTimeout(timeout); | |
| timeout = null; | |
| previous = now; | |
| result = func.apply(context, args); | |
| } else if (!timeout) { | |
| timeout = setTimeout(later, remaining); | |
| } | |
| return result; | |
| }; | |
| }; | |
| var socket = io.connect(); | |
| return { | |
| on: function (eventName, callback) { | |
| socket.on(eventName, throttle(function () { // limit to once every 500ms | |
| var args = arguments; | |
| $rootScope.$apply(function () { | |
| callback.apply(socket, args); | |
| }); | |
| }, 500)); | |
| } | |
| // ... | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment