Skip to content

Instantly share code, notes, and snippets.

@PatrickJS
Created June 17, 2014 03:51
Show Gist options
  • Save PatrickJS/79f0bf78d7b1856bd5c6 to your computer and use it in GitHub Desktop.
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
//
// 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) };
}
//
// 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);
};
}
//
// 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