Daily Challenge — Avoid Infinite Loop

A frontend quiz: modify the code to avoid an infinite loop, with analysis and solutions (Web Worker, async approaches).

Oct 29, 2020 · 1 min read · 167 Words · -Views -Comments · Programming
JavaScript 🇨🇳 阅读中文版
Read with AI

Choose an AI assistant

ChatGPT Open in a new tab with the article link and prompt
Claude Copy the prompt, then open Claude

Open Claude
Trouble reading the article?

If the prompt is missing, copy the full prompt below into your AI assistant. If the AI cannot read the article, paste the visible passage you want to discuss and add your question.

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

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover