0

I am trying following and expecting setTimeout to be executed every second for different index. I am able to achieve it thru bind method as commented, however when I use IIFE for the same, it is giving expected output but without any delay. Can anyone suggest correct implementation for the same.

function count(){
    for(i=0;i<5;i++){
        //var f = console.log.bind(null, i); //WORKING AS EXPECTED

        var f = ((index)=>{
            console.log(index);
        })(i);
        setTimeout(f, 1000*i);
    }
} 
count();

//OUTPUT (Without any delay)
0
1
2
3
4
Saad Usmani
  • 173
  • 14
  • 1
    Have the *whole body* of the loop be an IIFE, if you really want to go that route (though you should use `let i` instead). Eg `for(...){ ((index) => { setTimeout(() => console.log(index), 1000 * i) })(i) }` – CertainPerformance Nov 11 '19 at 08:33
  • 1
    your `f` should be a function, so there must be _two_ arrows: `var f = (index => () => console.log(index))(i)` – georg Nov 11 '19 at 08:40

0 Answers0