There is a function with a classic counter in closure:

function sliding(arr) { var i = 0; return function() { arr[i].style.opacity = 0; if(i == arr.length - 1) { arr[0].style.opacity = 1; } else { arr[i+1].style.opacity = 1; } i++; if(i == arr.length) { i = 0; } console.log(i); } } 

and code using this function:

 function move(item, step) { for(var i = 0; i < item.length; i++) { (function(i, step) { var f = sliding(item[i]); //вот здесь использую замыкание setTimeout(f, step) // и вызываю новую функцию через таймер, по идее перемменная `i` сохраненная в замыкании должна увеличиваться...А она всегда равна единице })(i, step); step += 300; } } setInterval(move.bind(this, self.imgs, 2000), 4000); 

Why does not the variable in the closure increase?

  • item [i] is an array? - Vlad from Moscow
  • @Vlad from Moscow yes - pepel_xD February
  • @Vlad from Moscow, inside it, a detour is done, and the counter which increases with each call is needed to access the elements of this array, only it increases at the first start, and it remains equal to one .... - pepel_xD
  • @pepel_xD, let me guess: the console always displays 1 ? - Dmitriy Simushev
  • four
    My crystal ball showed that causing var f = sliding(item[i]); every time you create a new closure , with var i = 0; . So he prints one every time ... Can we consider the remote debugging session closed? - Dmitriy Simushev

0