2013-10-30 37 views
1

中的變量我打電話給方法bullet.fire();在這種方法中,我有this.i ++,唯一的麻煩是this.i不會在每次迭代時更新,爲什麼?在一個循環中更新方法調用

function projectile(){ 
    this.i = 20; 
} 

projectile.prototype.fire = function(){ 
    this.i++; 
    //shows value of this.i in a div 
    document.getElementById("info").innerHTML = this.i; 
} 

在循環

if(typeof(bullet) == "undefined"){ 
    var bullet = new projectile(1); 
} 

bullet.fire(); 
+2

顯示完整循環代碼 –

+1

我複製並運行代碼(不'的document.getElementById(「信息」)的innerHTML = this.i'和它的工作如預期 –

+0

它更新正常,它只是一次全部更新,所以你不會看到它更新。在循環中放置一個'alert(bullet.i)';你會看到它工作正常。 –

回答

2

它確實火了!

由於兩個原因,您看不到進度。首先,沒有延遲,所以它瞬間發生。其次,JavaScript在一個同步線程中工作。在線程完成之前,接口(HTML)不會刷新。

您可以通過使用JavaScript異步執行方法之一來中斷線程。 setInterval一個實例:

<div id="info"></div> 
<script type="text/javascript"> 
function projectile(){ 
    this.i = 20; 
} 

projectile.prototype.fire = function(){ 
    this.i++; 
    //shows value of this.i in a div 
    document.getElementById("info").innerHTML = this.i; 
} 

var i = 3, bullet = new projectile(1), timer; 

timer = setInterval(function() { 
    bullet.fire(); 
    if (--i <= 0) clearInterval(timer); 
}, 300); 
</script> 

In action on fiddle