Reputation: 55729
The following code is from Essential JavaScript Design Patterns For Beginners. Why is the setTimeout function used here?
var pubsub = {};
(function(q) {
var topics = {},
subUid = -1;
q.publish = function(topic, args) {
if (!topics[topic]) {
return false;
}
setTimeout(function() {
var subscribers = topics[topic],
len = subscribers ? subscribers.length : 0;
while (len--) {
subscribers[len].func(topic, args);
}
}, 0);
return true;
};
q.subscribe = function(topic, func) {
if (!topics[topic]) {
topics[topic] = [];
}
var token = (++subUid).toString();
topics[topic].push({
token: token,
func: func
});
return token;
};
q.unsubscribe = function(token) {
for (var m in topics) {
if (topics[m]) {
for (var i = 0, j = topics[m].length; i < j; i++) {
if (topics[m][i].token === token) {
topics[m].splice(i, 1);
return token;
}
}
}
}
return false;
};
}(pubsub));
Upvotes: 4
Views: 318
Reputation: 340733
This way the publish
function returns immediately, in some way scheduling given code block to be executed immediately later (asynchronously).
Looks like it notifies a bunch of listeners, so the author wanted to run the notification loop later, not blocking the publish
code. Also note that the result of notification (if any) is not needed for the client code.
A side effect is that if one of the subscribers throw an exception, the publish
method is not affected (different call stack).
Maybe it is not idiomatic, but it is quite common pattern in JavaScript. Sometimes it is also used to let other events/timeout to run - especially in very long-running function.
Upvotes: 2