This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Calling functions with setTimeout()
(6 answers)
Closed 6 years ago.
I am trying to set a delay in the for loop in javascript. I want it to log i, have a delay, then log i, and so on. My question is, why does the following code work, having a function return a function as can be seen below:
for (var i = 1; i <= 5; i++) {
var tick = function(i) {
return function() {
console.log(i);
}
};
setTimeout(tick(i), 500 * i);
}
And the following code not work as expected:
for (var i = 1; i <= 5; i++) {
var tick = function(i) {
return console.log(i);
};
setTimeout(tick(i), 500 * i);
}
It prints out all the values in the for loop at once. Could someone please explain why this happens?
In both pieces of code, tick(i) is executed immediately in each loop
The difference is, that in the first example, tick(i) returns a function, which is called by setTimeout, and that outputs to the console
In the second example, the console.log is called immediately, undefined is returned, and setTimeout does nothing once the timeout has triggered as the given argument is not a function (or a string to be eval'd)
Related
This question already has answers here:
Does return stop a loop?
(7 answers)
Closed 2 years ago.
So, I am a beginner in JavaScript and I was just playing around by creating some functions!
why does if returned there is a different answer and why does if console logged there is a different answer!
SO IF I CONSOLE LOG THIS👇
const ex = (arra1) => {
for (let i = 0; i < arra1.length; i++) {
console.log(arra1[i]);
}
};
ex([1, 2, 3]);
answer for the above function is 1 2 3
BUT IF RETURN THIS👇
const ex = (arra1) => {
for (let i = 0; i < arra1.length; i++) {
return arra1[i];
}
};
console.log(ex([1, 2, 3]));
But the answer for this above function is 1
return will stop the execution immediately. As per MDN,
When a return statement is used in a function body, the execution of the function is stopped. If specified, a given value is returned to the function caller.
In the first example you are not returning anything but just logging the each value of the array.
console.log(arra1[i]);
In the second example you are just using return in the loop so in the first iteration the function will return a value which is first element of array. return statement just ends the further execution of the function.
return terminates the function and the loop, stopping after the first iteration
In the first example you don't terminate anything, so you end up iterating over everything
This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 2 years ago.
I have this code.
for (var i = 1; i <= 5; i++) {
setTimeout(function () {
console.log(i);
}, 1000);
}
I don't understand the output from this lines of code:
The output in the console is number 6,and it says that is repeated five times.
If i use the let keyword for "i" then i get the output that i expect,
1,2,3,4,5 after one second
Why is that ?
var has scoping issues and that's why let was introduced.
In your for loop you are defining i, but actually it's stuck to the global scope, and after 1 second, the for loop would actually be done, and when the setTimeout callback is fired, i would have already reached 6 and it's read from the global scope.
In a nutshell, because i is stuck to the upper scope of for, each iteration modifies the calue of i and doesn't create another i.
If you change var to let, the issue is resolved.
setTimeout is async hence will execute after the loop is done, that s why you have i=6, put it in a self invoking function to retain the value of i or use let instead of var in your loop
for (var i = 1; i <= 5; i++) {
((i) => setTimeout(function() {
console.log(i);
}, 1000))(i)
}
for (let i = 1; i <= 5; i++) {
setTimeout(function () {
console.log(i);
}, 1000);
}
This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
setTimeout in for-loop does not print consecutive values [duplicate]
(10 answers)
Closed 2 years ago.
for (var i = 0; i <= 100; i++) {
setTimeout(function() {
celsiusToFahrenheit(i);
}, 1000);
}
I'd like to make the celsius function run every second for 100 times but somehow it does not work and I have no idea why.
Pls halp.
That loop will create 100 setTimeout that all run at virtually the same time since the loop will complete in a few milliseconds.
Multiply the duration by i to increment it so the durations will be multiples of 1000.
You need to use let instead of var to block scope i
for (let i = 0; i <= 100; i++) {
setTimeout(function() {
celsiusToFahrenheit(i);
}, 1000 * i);
}
This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
How do JavaScript closures work?
(86 answers)
Closed 7 years ago.
I'm writing a for loop in Javascript. The desired goal is to print out 0, 1, 2 with a 3 second gap in between.
for (var i=0; i<3; i++) {
console.log(i);
}
This prints everything out as expected, with no pause. But when I add in a setTimeout:
for (var i=0; i<3; i++) {
setTimeout(function() {console.log{i},3000*i}
}
The result is that it prints out 3, 3, 3 with a 3 second gap. The pause worked, but it looks like its completing the loop before the right numbers can get printed.
You're exactly right that the loop is getting completed before the setTimeout calls run. Since all of your timeout functions reference i, they're all going to print out 3. The way to fix this is to capture the value of i in a closure.
for (var i = 0; i < 3; i++) {
(function(index) {
setTimeout(function() {
console.log(index);
}, 3000 * index);
})(i); // Instantly call the function and pass the value of i
}
This question already has answers here:
How do JavaScript closures work?
(86 answers)
Closed 7 years ago.
This is an example from a blog post by Avaylo Gerchev that addresses IIFE's. The following block of code returns 4 repeated 'undefined' responses by design:
function printFruits(fruits){
for (var i = 0; i < fruits.length; i++) {
setTimeout( function(){
console.log( fruits[i] );
}, i * 1000 );
}
}
printFruits(["Lemon", "Orange", "Mango", "Banana"]);
Avaylo then shows how to produce what (to me) would have been the expected output of the first code block (it outputs the values of the array):
function printFruits(fruits){
for (var i = 0; i < fruits.length; i++) {
(function(){
var current = i; // define new variable that will hold the current value of "i"
setTimeout( function(){
console.log( fruits[current] ); // this time the value of "current" will be different for each iteration
}, current * 1000 );
})();
}
}
printFruits(["Lemon", "Orange", "Mango", "Banana"]);
I understand that the IIFE creates a new scope. What I don't understand is the reason why the first block of code doesn't produce the (again, to me) expected output of returning the values in the array. I've been staring at this for a few days now, thus I conclude that my javascript knowledge is missing something fundamental.
Thank you for any insight!
In the first code block, the variable "i" is not accessible by the closure because setTimeout only defines what code to run but doesn't actually run it on definition, only later.
Having the closure there and running it immediately (with the parentheses () at the end) is a way to save the value of "i" in each iteration so that when setTimeout runs, it can access it.