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?
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?
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
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]);
Try this
list = [1000,2000,3000,4000];
for (var i = 1; i <= 3; i++) {
(function(index) {
setTimeout(function() { alert(index); }, i * list[i]);
})(i);
}