I'm implementing a simple logger in JavaScript that collects messages when certain events happen on the page (a button is clicked, DOM is changed, etc), and all the collected messages are periodically sent to the server using AJAX calls:
var Logger = function () {
var messages = [];
var flush = function () {
if (messages.length) {
$.post("receive-logs.php", { messages: messages.toString() });
messages = [];
}
};
return {
init: function () {
setInterval(flush, 5000);
},
addMessage: function (message) {
messages.push(message);
}
};
}();
Logger.init();
// Usage example:
// $("#button1").on("click", function () { Logger.addMessage("button1 clicked"); })
The thing I am concerned with in this implementations is whether messages can get "lost" if addMessage
is called after $.post
but before messages = []
.
In many articles I've read that JavaScript runs in a single-threaded environment, and thus developers never need to worry about stuff like locking or concurrency control. Which is confusing, because I see no reason why the situation I described above is impossible.
My question is: is the message loss possible in this case and how do I avoid it?