DEV Community

Cover image for Destructuring Tweets - Episode 8 - Timeout!

Destructuring Tweets - Episode 8 - Timeout!

odddev profile image Kai ・1 min read

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

Snippet of the Week

This week's snippet is from Catalin Pit:

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

for (let num of numbers) {
  setTimeout(() => console.log(num), num);
Enter fullscreen mode Exit fullscreen mode

The author defines and initializes an array holding a bunch of random numbers. Afterward, we iterate over each of them 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:








Enter fullscreen mode Exit fullscreen mode

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.


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.

Snippet Summary

Discussion (0)

Editor guide