Unable to find the mistake in setInterval [duplicate] - javascript

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 5 years ago.
I have this array:
var arr = [];
var i =

1) There:
setInterval ( function push(arr) {arr.push(i+1)} , 5*1000)
you're shadowing the arr variable (that is declaring a new variable which hides the external one). You're thus pushing to undefined. There's of course the same problem when you read the values.
2) If you always push i+1 you always push 1. You probably want i++
Simply do
setInterval ( function push() {arr.push(i++)} , 5*1000)

Related

question about scope, closures and Let variables [duplicate]

This question already has answers here:
setTimeout in for-loop does not print consecutive values [duplicate]
(10 answers)
JavaScript closure inside loops – simple practical example
(44 answers)
What is the difference between "let" and "var"?
(39 answers)
Closed 1 year ago.
I am reading about closures, and I found these small exercises that I solved by chance, but I don't understand why they work.
The exercise is :
for (var i = 0; i < 3; i++) {
setTimeout(function log() {
console.log(i); // What is logged?
}, 1000);
}
I get that 3 will be printed 3 times because the value captured by log() when the for() ends.
Additionally, it was asked how to fix it for the console to print 0,1,2, and I found (by chance, to be honest), that it works by doing :
for ( let i =0 ...
But I guess because Let is block scoped, but i don't really know how to explain it in simple words.
The variables defined with let are blocked scope which means once you go out of the bracket it loses its value and if you try to access it will throw you an error. So, when the for is running the, i present in the console.log() will store the value for it like 0,1,etc.
whereas in the var part the var will be stored in memory and when the timeout is about to expire it will access the variable i in the memory and print whatever is there for that variable at that time.

Event Listener with Parameter created Dynamically [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
let keyword in the for loop
(3 answers)
What is the difference between "let" and "var"?
(39 answers)
Closed 2 years ago.
I am dynamically creating a series of buttons using a for loop and adding an Event Listener to them as follows (I have excluded several lines of code for simplicity). However, upon using any of the buttons after creation, the parameter "i" always corresponds to the value "i" had when it exited the for loop. I have seen numerous proposed solutions online, but none of them are actually working.
for (var i = 0; i < size; i++) {
button.addEventListener('click', () => this.Purchase(i))
}
You should use let i = 0 instead of var i = 0 in order to have the i variable be scoped to the loop. With var, i is scoped to the innermost function, which means it constantly gets overwritten. See here for more info.

Array function of JavaScript && Rest Parameter? [duplicate]

This question already has answers here:
What does this symbol mean in JavaScript?
(1 answer)
What is the meaning of "...args" (three dots) in a function definition?
(6 answers)
Closed 5 years ago.
I was reading the JavaScript Docs I found the Array function section one Example that I could not understand properly. Because I am learning Programming.
function multiply(multiplier, ...theArgs){
return theArgs.map(x=> multiplier*x);
}
var arr = multiply(2,1,2,3);
console.log(arr);
Above example is giving
2,4,6
My first question why is used 3 dots(...) before function argument name (...theArgs) for? And How did it calculate 2,4,6?
And the second Question is about rest parameter. What does the rest parameter use in Array Function?
I would be glad if anyone can give me some real-life object example to understand this Problem

Set timeouts on all elements in an array in node.js [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 6 years ago.
node.js newbie here. I'm looping through an array of objects, and setting a timeout for doing some ops using each object individually, the timeout for each objects also depends on some key-value within the object. The code is here:
for (var idx in arr) {
var obj = arr[idx];
interval = obj['key'];
setTimeout(function(){my_func(obj);}, interval);
}
Now what is failing here is that whenever a timeout occurs and the code block for my_func is called, it always acts on the last object in the array, probably because the variable 'obj' at that time points to it. How do I get around this? I am guessing I need a pass by reference, or something similar. Please point me in the right direction if I'm missing something here.
You will need to use closure for this:
for (var idx in arr) {
var obj = arr[idx];
(function( obj ){
interval = obj['key'];
setTimeout(function(){my_func(obj);}, interval);
})( obj );
}//for()

Looping JS variable doesn't show the correct value inside the function [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Doesn't JavaScript support closures with local variables? [duplicate]
(7 answers)
Closed 8 years ago.
I need to do the following task. But this always alerts only "5" instead of 1,2,3,4 and 5. How can I fix this? Please help.
for(var x=1; x<=5; x++){
something.load(function(result){
alert(x);
});
}
This is due to closure. When the callback is runned, it will alert the variable in its current state (so after the loop).
To fix this, you can create a new closure which'll keep the variable state.
for(var x=1; x<=5; x++){
(function(x) {
something.load(function(result){
alert(x);
});
}(x));
}
For a more complete explanation of Closure, you can refer to this SO question: How do JavaScript closures work?
Or this article by a member of TC39 (EcmaScript standard body) http://www.2ality.com/2013/05/quirk-closures.html

Categories

Resources