Created
June 17, 2014 03:51
-
-
Save PatrickJS/79f0bf78d7b1856bd5c6 to your computer and use it in GitHub Desktop.
PubNub Rate Limiting vs. Throttling Messages in AngularJS http://stackoverflow.com/questions/18364918/throttling-pubnub-requests-in-angluarjs
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
// | |
// Listen for messages and process all messages at steady rate limit. | |
// | |
pubnub.subscribe({ | |
channel : "hello_world", | |
message : limit( function(message) { | |
// process your messages at set interval here. | |
}, 500 /* milliseconds */ ) | |
}); | |
// | |
// Rate Limit Function | |
// | |
function limit( fun, rate ) { | |
var queue = []; | |
setInterval( function() { | |
var msg = queue.shift(); | |
msg && fun(msg); | |
}, rate ); | |
return function(message) { queue.push(message) }; | |
} |
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
// | |
// Listen for events and process last message each 500ms. | |
// | |
pubnub.subscribe({ | |
channel : "hello_world", | |
message : thrimit( function( last_message, all_messages ) { | |
// process your last message here each 500ms. | |
}, 500 /* milliseconds */ ) | |
}); | |
// | |
// Throttle + Limit Function | |
// | |
function thrimit( fun, rate ) { | |
var last; | |
var queue = []; | |
setInterval( function() { | |
last !== null && fun( last, queue ); | |
last = null; | |
queue = [] | |
}, rate ); | |
return function(message) { | |
last = message; | |
queue.push(message); | |
}; | |
} |
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
// | |
// Listen for events and process last message each 500ms. | |
// | |
pubnub.subscribe({ | |
channel : "hello_world", | |
message : throttle( function(message) { | |
// process your last message here each 500ms. | |
}, 500 /* milliseconds */ ) | |
}); | |
// | |
// Throttle Function | |
// | |
function throttle( fun, rate ) { | |
var last; | |
setInterval( function() { | |
last !== null && fun(last); | |
last = null; | |
}, rate ); | |
return function(message) { last = message }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment