本文介绍了Javascript关闭“存储”值在错误的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个计数器逐渐增加。以下工作:

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);
    setTimeout( "_change_score_by("+diff+");" /* sigh */,
                step * 25);
    points -= diff;
    step++;
  }
}

但是,它使用隐式eval。邪恶!让我们使用一个闭包,对吧?

However, it uses an implicit eval. Evil! Let's use a closure instead, right?

function _award(points){    
  var step = 1;
  while(points){
    var diff = Math.ceil(points / 10);
    setTimeout( function(){ _change_score_by(diff); },
                step * 25);
    points -= diff;
    step++;
  }
}

显然,这不起作用。所有的闭包创建的抓住最后的值 diff 已经在函数 - 1.因此,所有匿名函数将增加计数器1,例如,<$ c $

Obviously, this doesn't work. All closures created catch the last value diff has had in the function -- 1. Hence, all anonymous functions will increase the counter by 1 and, for example, _award(100) will increase the score by 28 instead.

如何正确地执行此操作?

How can I do this properly?

推荐答案

这是一个已知的问题。但是你可以在每个循环迭代中轻松地创建一个闭包:

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);

这篇关于Javascript关闭“存储”值在错误的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 14:32