Destructuring Tweets – Episode 8 – Timeout!

Welcome to one of the articles about destructuring a coding quiz from Social Media. This time, we check out a very funny sorting algorithm. Be prepared to order numbers with timeouts!

The Snippet

const numbers = [29, 11, 201, 7, 99, 912, 39, 31];

for (let num of numbers) {
  setTimeout(() => console.log(num), num);
}

The author defines and initializes an array holding a bunch of random numbers. Afterward, we iterate over each to set a timer to execute a simple console.log. Each timer gets executed after so many milliseconds, as the value of the individual array item is.

The Output

No big surprise here. Well, at least if you are familiar with the setTimeout API and gave the snippet some thought. Indeed you get a list of sorted integers:

7

11

29

31

39

99

201

912

The Analysis

The idea behind this snippet is glorious! Instead of comparing the values and ordering them, you just let time decide. The highest value will delay the callback most, thus, be printed last.

Appendix

Don't take this snippet seriously! It's meant to be a joke. It would be best if you never utilized setTimeout like that. It's solely for, well, “setting a timer”. Never abuse this behavior.

Further Reading