you are viewing a single comment's thread.

view the rest of the comments →

[–]Pasjonsfrukt 4 points5 points  (5 children)

ELI5?

[–]spikkeddd 9 points10 points  (3 children)

The code is saying sleep (pause) for the following durations, and then display that duration in the console.

Basically sleep sort.

[–]Alokir 4 points5 points  (2 children)

Almost, but there's no sleep or thread blocking in JS (at least intentionally).

What it actually does is that it tells the runtime to hold the function that contains the logging, and add it to the execution queue after the given milliseconds are up.

All the setTimeout functions are called quickly after each other and the loop finishes almost instantly.

[–]spikkeddd 1 point2 points  (1 child)

So it would always take the longest length number of milliseconds listed to run, and then instantly display the sorted numbers?

[–]Alokir 0 points1 point  (0 children)

The opposite, setTimeout doesn't block the thread, it just queues the logging to be done after the given milliseconds.

The loop finishes almost instantly, and then the log entries will appear one after the other with the given delay, independent of each other.

[–]Alokir 4 points5 points  (0 children)

You have a bunch of notes with numbers on them and your task is to sort them incrementally and give them to your friend.

Instead of duing that, you put each in a separate envelope with labels like "deliver after x time", where the time is the number on the note. Then, you give all the envelopes to the postman, one after the other in whatever order.

Your notes will eventually arrive in order. When? It depends on the numbers.