2011-11-24 105 views
0

可能重複:
function in setInterval() executes without delaysetTimeOut無法正常工作?

我想使用的setTimeout來馬蹄蓮功能每X毫秒,但似乎它只是怪胎和計數快得令人難以置信,無論什麼時間內我將它設置爲?難道我做錯了什麼?

var Count = 0; 
var GameRunning = 0; 

var lblTimer = Titanium.UI.createLabel({ 
    color:'#999', 
    text:'I am Window 1', 
    font:{fontSize:20,fontFamily:'Helvetica Neue'}, 
    textAlign:'center', 
    width:'auto', 
    height: 25, 
    top: 25 
}); 

var btnStartGame = Titanium.UI.createButton({ 
    title: 'Start', 
    width: 50, 
    height: 25, 
    top: 75 
}); 

function RunGame() { 
    Count++; 
    lblTimer.text = Count; 
    x = setTimeout(RunGame(), 100000); 
} 

function StartGame() { 
    if(GameRunning==0) 
    { 
    GameRunning = 1; 
    RunGame(); 
    } 
    else 
    { 
    // Stop the game. 
    GameRunning = 0; 
    Count = 0; 
    } 
} 

function GameTimerCount() { 
    Titanium.API.info("inside GameTimerCount"); 
    Count++; 
    lblTimer.text = "RUNNING: " + Count; 
} 

btnStartGame.addEventListener('click',function(e) 
{ 
    Titanium.API.info("button clicked"); 
    StartGame(); 

    //var test = setInterval("GameTimerCount()",100); 
}); 

// Add objects to window 
Titanium.UI.currentWindow.add(lblTimer); 
Titanium.UI.currentWindow.add(btnStartGame); 
+3

請參閱[函數在setInterval()執行沒有延遲](http://stackoverflow.com/questions/7858262/function-in-setinterval-executes-without-delay/7858280#7858280)。 TLDR:刪除括號:'x = setTimeout(RunGame(),100000);'=>'x = setTimeout(RunGame,100000);' – Esailija

回答

6

您的setTimeout調用改成這樣:

setTimeout(RunGame,1000); 

RunGame()返回void所以有setTimeout(RunGame(),1000);實際上更類似於setTimeout(void,1000);這確實沒有什麼。 setTimeout通過使用函數指針來了解要執行的函數。

+0

JavaScript中沒有'void'返回值。不明確返回的函數返回'undefined'。請注意,有*是'空'關鍵字,但這是一個完全不同的東西:) –

+1

這是一個隱喻的空白,以防他有C經驗:) –