-1

I expected the below code snippet to print out the console log after pausing for every 1 sec.

But the code snippet executes instantaneously (prints out 100 times though) with the following output.

Can someone tell me what I am doing wrong ?

enter image description here

let i = 0;
for (; i < 100; i++) {
  setTimeout(console.log("test"), 1000);
}
console.log('Loop Done');
console.log('Value of i ==>' + i);
mplungjan
  • 169,008
  • 28
  • 173
  • 236
VPY
  • 463
  • 8
  • 21

2 Answers2

1

As I mentioned in my comment, you are calling console.log right away, and also setTimeout is asynchronous and thus it is nonblocking.

One of the correct ways to do it would be

for (let i = 0; i < 100; i++) {
    setTimeout(() => console.log("test"), 1000 * i);
}
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
1

You are actually setting a timeout for the return value of console.log, i.e., undefined, instead of an actual function.

setTimeout requires a function as the first argument in order for it to work. You have passed undefined. To fix this, there are 2 ways.

Pass a function that calls console.log

setTimeout(function () {
  console.log("test");
}, 100);

In ES6, that would be much shorter:

setTimeout(() => console.log("test"), 100);

Bind arguments to console.log

setTimeout(console.log.bind(undefined, "test"), 100);

bind()-ing arguments to a function is like telling the function to to execute with the arguments we are giving it. The function is not executed immediately when you call bind, but the arguments are stored.

Also, as a side-note, the first argument we passed for bind, i.e., undefined, is the this value for the function. We do not care about the this value of console.log, and we want to pass only "test", we write undefined as the this value.

frick
  • 166
  • 9