setTimeOut

Guess the output

				
					for (let i = 0; i < 5; i++) {
  setTimeout(() => {
    console.log(i);
  }, 1000);
}
//0 1 2 3 4

for (var i = 0; i < 5; i++) {
  setTimeout(() => {
    console.log(i);
  }, 1000);
}
// 5 5 5 5 5
				
			

Guess the output

				
					const logNumbers = () => {
  console.log(1);
  setTimeout(() => {
    console.log(2);
  }, 1000);
  setTimeout(() => {
    console.log(3);
  }, 0);
  console.log(4);
};

logNumbers();
//output:- 1 4 3 2

				
			
				
					const logNumbers = () => {
  console.log(1);
  setTimeout(() => {
    console.log(2);
  }, 1000);
  setTimeout(() => {
    console.log(3);
  }, 1000);
  console.log(4);
};

logNumbers();
//output:- 1 4 2 3

				
			

Priority is highest for Promise than setTimeout
Output is - 1 4 5 3 2

				
					const logNumbers = () => {
  console.log(1);
  setTimeout(() => {
    console.log(2);
  }, 1000);
  setTimeout(() => {
    console.log(3);
  }, 0);

  Promise.resolve().then(() => {
    console.log(5);
  });

  console.log(4);
};

logNumbers();
//output:- 1 4 5 3 2
				
			

Guess the output

				
					const arr = [2, 4, 6, 8, 10000];
for (let i = 0; i < arr.length; i++) {
  setTimeout(() => {
    console.log(arr[i]);
  }, arr[i]);
}

//output:- 2 4 6 8 10000
				
			

Leave a Comment