Frontend Development 6 min read

How a Joke Sorting Algorithm Reveals JavaScript’s Event Loop Mechanics

Discover how a playful setTimeout‑based sorting trick leverages JavaScript’s event loop to produce correct ordering, while explaining the core concepts of synchronous vs asynchronous tasks, the execution stack, task queue, and why this method isn’t practical for large datasets.

MaoDou Frontend Team
MaoDou Frontend Team
MaoDou Frontend Team
How a Joke Sorting Algorithm Reveals JavaScript’s Event Loop Mechanics

Background

By chance I saw a joke sorting algorithm in a tech group. At first glance it looked like a parody, but it actually produced the correct sorted result, prompting me to investigate its inner workings.

Event Loop Introduction

We know JavaScript runs on a single thread. The thread executes code sequentially, but long‑running tasks such as network requests or I/O would block the thread and freeze the UI. To avoid this, JavaScript distinguishes between synchronous and asynchronous tasks.

During execution, synchronous tasks are placed on the execution context stack and run on the main thread in order. When an asynchronous task is encountered, it is suspended and the engine continues with the next synchronous task. Once the asynchronous operation completes, its callback is added to the task queue.

When the call stack becomes empty, the main thread checks the task queue; if there are pending callbacks, the oldest one is moved to the call stack for execution. This continuous cycle is known as the Event Loop.

The diagram shows that JavaScript creates a heap and a stack at runtime; asynchronous tasks like Ajax or setTimeout are suspended, their results are placed in the task queue, and the main thread repeatedly pulls tasks from the queue into the call stack.

"Sorting" Code Analysis

The key keyword linking the joke algorithm to the Event Loop is setTimeout . Each element of the array schedules a callback with a delay proportional to its value. Smaller values have shorter delays, so their callbacks enter the task queue earlier, resulting in a sorted order when the callbacks finally execute.

Ignoring the timing, the algorithm traverses the array once, giving it O(n) time complexity. It is also stable because equal values retain their relative order. The function can be refactored to accept a callback that receives the sorted array:

<code>function eventLoopSort(list, callback) {
  var newList = [];
  var sum = 0;
  list.forEach(item => {
    setTimeout(() => {
      newList.push(item);
    }, item * 100);
    sum += item;
  });
  setTimeout(() => {
    callback && callback(newList);
  }, sum * 100);
}
var list = [1, 1, 4, 6, 2, 3, 9, 8, 7];
eventLoopSort(list, data => {
  console.log(data); // [1, 1, 2, 3, 4, 6, 7, 8, 9]
});
</code>

Problem Summary

Although the explanation is serious, the sorting method remains a joke and is unsuitable for real‑world code. With large data sets, the cumulative setTimeout delays become significant, and the execution time of the code itself can outweigh the intended timing differences, causing incorrect ordering.

The author who first wrote this “joke” clearly understands the browser’s execution model, and the article aims to use this humorous example to help readers learn about the Event Loop.

JavaScriptasynchronousSorting Algorithmevent-loopsetTimeout
MaoDou Frontend Team
Written by

MaoDou Frontend Team

Open-source, innovative, collaborative, win‑win – sharing frontend tech and shaping its future.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.