J'ai remarqué quelque chose que je ne peux pas tout à fait expliquer. J'ai fait ce code javascript qui pousse ou réduit une boîte bleue. Le script est ici:Javascript setInterval question
var animated = {
timer : null,
el : document.getElementById("divNavyBox"),
startGrowAnimation : function() {
this.stopAnimation();
this.timer = setInterval(
animated.doAnimation(5), 10);
},
startShrinkAnimation : function() {
this.stopAnimation();
this.timer = setInterval(function() {
animated.doAnimation(-5);
}, 10);
},
stopAnimation : function() {
clearInterval(this.timer);
},
doAnimation : function(amount) {
var size = this.el.offsetWidth;
if ((amount > 0 && size < 200) || (amount < 0 && size > 0)) {
this.el.style.width = size + amount + "px";
this.el.style.height = size + amount + "px";
} else {
this.stopAnimation();
}
}
};
Lorsque la méthode startGrowAnimation de la classe d'animation est appelée, la boîte jusqu'à ce qu'il pousse visuellement atteint une certaine largeur et la hauteur. Il s'arrête ensuite. Le code startGrowAnimation se trouve ci-dessous:
startGrowAnimation : function() {
this.timer = setInterval(function() {
animated.doAnimation(5);
}, 10);
}
Ce code fonctionne très bien. Cependant, je ne comprends pas pourquoi il est nécessaire de mettre une fonction anonyme dans le paramètre au lieu de simplement la fonction d'appel normale. Alors, je l'ai remplacé le code ci-dessus avec le code ci-dessous:
startGrowAnimation : function() {
this.stopAnimation();
this.timer = setInterval(animated.doAnimation(5), 10);
},
Lorsque j'utilise ce code, pour une raison quelconque, la boîte ne fait qu'accroître la taille de cinq pixels à chaque fois que la méthode startGrowAnimation est appelée. Alors, pourquoi est-il nécessaire d'inclure la méthode startGrowAnimation dans un appel de fonction anonyme dans ce cas?
+1 - Grande question qui suscite la réflexion! – jmort253