Presented by @tlhunter@mastodon.social
Distributed Systems with Node.js: bit.ly/34SHToF
setTimeout()
and setInterval()
The Event Loop is named after repeatedly taking work from the queue and making new stacks.
Image Credit: Mozilla Developer Network:
http://mzl.la/Y5Dh2x
function run() {
console.log("Adding code to the stack");
setTimeout(function c() { // c() Added somewhere in Heap
console.log("c() Running next code from queue");
}, 0);
function a(x) { // a() Added somewhere in Heap
console.log("a() frame added to stack");
b(x);
console.log("a() frame removed from stack");
}
function b(y) { // b() Added somewhere in Heap
console.log("b() frame added to stack");
console.log("Value passed in is " + y);
console.log("b() frame removed from stack");
}
a(42);
console.log("Ending work for this stack");
}
bit.ly/2kF3TMh
...
setTimeout(function() { console.log('A'); }, 0);
console.log('B');
setTimeout(function() { console.log('C'); }, 100);
setTimeout(function() { console.log('D'); }, 0);
var i = 0;
while (i < 200000000) { // Takes ~500ms to run this loop
var ignore = Math.sqrt(i);
i++;
}
console.log('E');
...
var LIMIT = 200000;
function drawMany() {
for (var i = 0; i < LIMIT; i++) {
output.appendChild(document.createElement('div'));
}
}
...
var LIMIT = 200000;
var CHUNK = 1000;
function drawFew(start, callback) {
for (var i = 0; i < CHUNK; i++) {
output.appendChild(document.createElement('div'));
}
if (start >= LIMIT) return callback();
setTimeout(function() {
drawFew(start + CHUNK, callback);
}, 0);
}
...
...
// main.js
var worker = new Worker('task.js');
worker.postMessage({iterations: 5000000000});
worker.onmessage = function(e) { console.log(e.data); };
// task.js
onmessage = function(e) {
var pi = 0, n = 1;
for (i = 0; i <= e.data.iterations; i++) {
pi = pi + (4/n) - (4 / (n + 2)); n += 4;
}
postMessage(pi);
};
var cluster = require('cluster');
var http = require('http');
if (cluster.isMaster) {
cluster.fork(); cluster.fork(); cluster.fork();
} else {
http.createServer(function(req, res) {
res.end("Hello World from: " + process.pid);
}).listen(80);
}
Distributed Systems with Node.js: bit.ly/34SHToF