Daily Challenge — Avoid Infinite Loop
·
1 min read
·
167
Words
·
-Views
-Comments
Here’s a frontend quiz: “Modify the code so it doesn’t cause an infinite loop.”
while (1) {
console.log(Math.random());
}
Analysis
First, keep in mind:
- JS is single-threaded
- There’s no true parallelism in JS, only concurrency
Therefore the loop above will run forever if executed on the main thread. To avoid blocking, we need asynchrony or multiple threads.
Solution
Based on the above, the fixes are straightforward.
Web Worker
- Web Workers run on separate threads, so they don’t block the main thread.
- As IE has been replaced by Edge, Worker support is solid across non-IE browsers — safe to use.
// main.js
const worker = new Worker('worker.js');
worker.onmessage = function (e) {
// handle the data received from the worker
};
// worker.js
while (1) {
const n = Math.random();
console.log(n);
if (n > 0.9) {
postMessage(n);
break;
}
}
Concurrent.Thread.js Library
If you can’t use Web Workers, this library simulates “multithreading” via asynchronous execution.
Concurrent.Thread.create(function () {
while (1) {
console.log(Math.random());
}
});
Library link — GitHub