Why is the setTimeout function used here?

The following code is from Basic 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)); 
+4
source share
1 answer

Thus, the publish function returns immediately, in some way planning a given block of code, which should be executed immediately (asynchronously).

It seems that he notifies a bunch of listeners, so the author wanted to start the notification cycle later, and not block the publish code. Also note that the result of the notification (if any) is not required for the client code.

A side effect is that if one of the subscribers throws an exception, the publish method has no effect (another call stack).

This may not be idiomatic, but it is a fairly common pattern in JavaScript. Sometimes it is also used to trigger other events / timeout - especially in a very long-running function.

+2
source

Source: https://habr.com/ru/post/1391513/


All Articles