Skip to content Skip to sidebar Skip to footer

Javascript Closure "stores" Value At The Wrong Time

I'm trying to have a counter increase gradually. The following works: function _award(points){ var step = 1; while(points){ var diff = Math.ceil(points / 10); setTi

Solution 1:

This is a known problem. But you can easily create a closure on each loop iteration:

(function(current_diff) {
    setTimeout(function() {_change_score_by(current_diff);},
               step * 25);
})(diff);

Solution 2:

Solving the Closure Loop Problem gets less messy with ECMAScript Fifth Edition's Function#bind method:

setTimeout(_change_score_by.bind(window, diff), step*25);

You can hack this feature into browsers that don't support it yet to get the benefit now.

Solution 3:

Nikita's approach works (thanks!), but personally I prefer changing it to this more explicit way:

function_schedule_score_change(diff, step){
  setTimeout( function(){ _change_score_by(diff) },
              step*25 );
}

function_award(points){    
  var step = 1;
  while(points){
    var diff = Math.ceil(points / 10);
    _schedule_score_change(diff, step);
    points -= diff;
    step++;
  }
}

Post a Comment for "Javascript Closure "stores" Value At The Wrong Time"