Last active
December 18, 2017 14:56
-
-
Save cvan/d82405ac5b0dddac0d5d to your computer and use it in GitHub Desktop.
a simple JS queue for queueing messages when offline
This file contains 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
<script src="queue.js"></script> |
This file contains 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
function connect() { | |
// This could be waiting on a script you're waiting to load | |
// (e.g., Google Analytics), or it could be waiting on the | |
// server to log the user in before processing some actions | |
// requested by the user. | |
return new Promise(function (resolve) { | |
// `setTimeout` to simulate a delay. | |
window.setTimeout(function () { | |
resolve(); | |
}, 150); | |
}); | |
} | |
connect().then(function () { | |
// Swap out the `send` function to do the real sending. | |
send = function send(msg) { | |
console.log('Sent message: ' + JSON.stringify(msg)); | |
}; | |
// Send any queued messages. | |
while (queue.length) { | |
send(queue.pop()); | |
} | |
}); | |
var queue = []; // A queue for messages to send once we connect to host. | |
function send(msg) { | |
// Turn a single message into an array of messages. | |
if (!Array.isArray(msg)) { | |
msg = [msg]; | |
} | |
// Queueing messages if we are not yet connected to host. | |
msg.forEach(function (msg) { | |
console.log('Queued message: ' + JSON.stringify(msg)); | |
// Prepend each message so we can treat the array like a queue. | |
queue.unshift(msg); | |
}); | |
} | |
send('hey'); | |
send('yolo'); | |
send('whatup'); | |
// These messagse will get sent immediately, bypassing the queue. | |
setTimeout(function () { | |
send('swag'); | |
}, 200); | |
setTimeout(function () { | |
send('shmoney'); | |
}, 400); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment