DEV Community

Mehul Lakhanpal
Mehul Lakhanpal

Posted on

Print sorted elements of an array using setTimeout

const arr = [4, 9, 2, 20, 1, 12];
arr.forEach(num => {
    setTimeout(() => console.log(num), num);
});
Enter fullscreen mode Exit fullscreen mode

Output:
1
2
4
9
12
20


Thanks for reading 💙

Follow @codedrops.tech for daily posts.

InstagramFacebook

Micro-Learning ● Web Development ● Javascript ● MERN stack

codedrops.tech

Discussion (1)

Collapse
rjitsu profile image
Rishav Jadon

This ain't a good approach, what if the array has bigger numbers?
Having a sort function inside of the setTimeout is better.