DEV Community

Shravan Kumar B
Shravan Kumar B

Posted on

2 5

Javascript's setTimeout can sort an array, how?

setTimeout function of the Web API's with Javascript; can sort an array.

Example:


[111,20,13,4,544,32,12,414,123].forEach((item) => {

   setTimeout(()=> console.log(item), item);

});
Enter fullscreen mode Exit fullscreen mode

The same works for negative as well,
Example:

let arr = [10, -100, 650, -25, 5, -50];

const min = -Math.min(...arr)

arr.forEach((item) => {
  setTimeout(() => console.log(item), item + min);
});

Enter fullscreen mode Exit fullscreen mode

Any guesses how?
Of course, not an efficient way to do it.

Clue: Call-Stack and Web API's

Top comments (1)

Collapse
 
stefanbc profile image
Stefan Cosma

I saw this on r/ProgrammerHumor the other day and initially thought it was a gimmick but then I reproduced it and yep it works. I did find some possible explanations here stackoverflow.com/questions/526798...

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series