DEV Community

Shravan Kumar B
Shravan Kumar B

Posted on

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...