的类中
我当前有一个循环,每秒都会对html元素进行动画,而最后一个动画完成后,我想接受用户输入:
playSequence(currentLevel) {
console.log("playing level " + currentLevel)
for (var q = 0; q < currentLevel; q++) {
(function(q) {
setTimeout(function() {
var active = '#' + sequence[q].toString(); //the div currently being animated
console.log(active);
var currentColor = $(active).css('background-color');
var newColor = currentColor.replace("0.6", "1.0");
$(active).animate({
backgroundColor: newColor
}, 100, function() {}).delay(900).animate({
backgroundColor: currentColor
}, 100, function() {
if (q === (currentLevel - 1)) {
console.log("done"); //this runs
this.getInput(1, currentLevel); //this does not
}
});
}, 1000 * q)
}(q));
}
}
最后一个动画后,"完成"了,但未调用getInput,因为函数开头的console.log未打印。
即使在上一个计时器完成后,它也不运行,即使在上面的控制台。
但是,如果我这样移动getInput,
playSequence(currentLevel) {
console.log("playing level " + currentLevel)
for (var q = 0; q < currentLevel; q++) {
(function(q) {
setTimeout(function() {
var active = '#' + sequence[q].toString(); //the div currently being animated
console.log(active);
var currentColor = $(active).css('background-color');
var newColor = currentColor.replace("0.6", "1.0");
$(active).animate({
backgroundColor: newColor
}, 100, function() {}).delay(900).animate({
backgroundColor: currentColor
}, 100, function() {
if (q === (currentLevel - 1)) {
console.log("done"); //this runs
}
});
}, 1000 * q)
}(q));
}
this.getInput(1, currentLevel); //this runs
}
然后getInput确实运行,但是它无法按照我的意愿运行
注意:这包含在React类中,而GetInput不是PlaySequence内部的方法,它们都在称为" Game"
@phpglue的评论有效,以防将来有人偶然发现答案:
如果您做var t = this;最重要的是您可以在其中使用t.getInput((