Sign up for Free !!
World's first open source developer community with
Ticketing System
let i; for (i = 0; i < 3; i++) { const log = () => { console.log(i); } setTimeout(log, 100); }
The output is 3,3,3 because the loop ends before the setTimeout function is called.
Also, don't declare a function expression inside a loop. It's a waste of time
So, if you want to print 0, 1, 2, ..., 14 and add some delay between printing, this should work:
const log = i => console.log(i) for(let i = 0;i < 15; i++){ setTimeout(log, 1000 * (i + 1), i); }
@mateigliga, Thanks for your answer.
Please Login/Register to write your answer !!!
The output is 3,3,3 because the loop ends before the setTimeout function is called.
Also, don't declare a function expression inside a loop. It's a waste of time
So, if you want to print 0, 1, 2, ..., 14 and add some delay between printing, this should work: