We can also get the expected result using bind:
const arr = [5,10,15,20,25];
for (var i=0; i<arr.length; i++) { setTimeout(function(i){ console.log(`Index: ${i}, element: ${arr[i]}`) }.bind(null, i),2000); }
Also works with a third argument of setTimeout function
for those who still don't get what is happening here .. read the following ==> https://flaviocopes.com/javascript-loops-and-scope/
Pls do video series on "Tricky Javascript Interview Questions" this topic
I do not get why it still does not work even if I change 2000 to zero inside the set time out.
Your email address will not be published. Required fields are marked *
Comment *
Name *
Email *
Website
Save my name, email, and website in this browser for the next time I comment.
© 2019 TucsonHouseOfCannabis
We can also get the expected result using bind:
const arr = [5,10,15,20,25];
for (var i=0; i<arr.length; i++) {
setTimeout(function(i){
console.log(`Index: ${i}, element: ${arr[i]}`)
}.bind(null, i),2000);
}
Also works with a third argument of setTimeout function
for those who still don't get what is happening here .. read the following ==> https://flaviocopes.com/javascript-loops-and-scope/
Pls do video series on "Tricky Javascript Interview Questions" this topic
I do not get why it still does not work even if I change 2000 to zero inside the set time out.