-1
list = [1000,2000,3000,4000];
for (var i = 0; i < 4; i++) {
    setTimeout(console.log('Hello'), list[i]);}

Why doesn't this code print out 'Hello' after the times in the list?

Paul
  • 139,544
  • 27
  • 275
  • 264
arij asad
  • 1
  • 2
  • 2
    you are passing the result of `console.log` to setTimeout` – Daniel A. White May 04 '16 at 20:25
  • 1
    Please don't edit your question if that edit makes existing answers obsolete. It would be better to ask a new question instead, but in this case that would also be a duplicate. – Paul May 04 '16 at 20:37
  • Also, I don't recommend passing a string to setTimeout. There are [many reasons that is a bad idea](http://stackoverflow.com/a/25259001/772035). – Paul May 04 '16 at 20:38
  • Particularly, you shouldn’t edit your question to _correct_ your code. – Sebastian Simon May 04 '16 at 20:39

3 Answers3

3

this is the right way to do it :

list = [1000,2000,3000,4000];
for (var i = 0; i < 4; i++) {
    setTimeout(function(){console.log('Hello')}, list[i]);}

because setTimeout accepts a callback function not an instruction

Akram Saouri
  • 1,179
  • 8
  • 15
1

You are calling console.log() immediately and passing the return value as the argument to setTimeout.

You should be passing a function. The bind() method will return a new function that calls log with the correct context and the arguments you specify.

setTimeout(console.log.bind(console, 'Hello'), list[i]);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

Try this

list = [1000,2000,3000,4000];
for (var i = 1; i <= 3; i++) {
    (function(index) {
        setTimeout(function() { alert(index); }, i * list[i]);
    })(i);
}
Wasiq Muhammad
  • 3,080
  • 3
  • 16
  • 29