2013-03-14 57 views
0

我有一個程序,其邏輯與我在這裏包含的虛擬樣本相同。我試過了一個簡單的while (1),它不運行(至少沒有顯示UI)。此示例基於變量設置運行while循環,該變量設置由應該終止循環的addEventListener()更改。但是,它的行爲與while (1)一樣。簡單地說,我需要做的是等待輸入密碼並確認它是匹配的。如果不是,我繼續循環。如果它匹配,程序將繼續執行另一個循環(樣本中未顯示),只要程序運行,該循環就需要運行。這第二個while根據用戶輸入運行幾個功能。每次有用戶輸入時,運行while的另一個循環。我更喜歡不使用另一個線程。看起來任何創建循環的邏輯反應方式都相同,即沒有執行或至少沒有可見的執行。換句話說,爲什麼不while (1)for (;;)工作!任何援助將不勝感激。如何在不殺死程序執行的情況下創建無限循環?

//app.js 
var debugText = Titanium.UI.createLabel({ 
    top: 600, 
    left: 0, 
    width: 500, 
    height: 100, 
    color: '#777', 
    font:{fontSize:40}, 
    hintText: 'debug text' 
}); 
var entryCodeText = Titanium.UI.createTextField({ 
    top: 300, 
    left: 0, 
    width: 400, 
    height: 100, 
    color: '#777', 
    font:{fontSize:40}, 
    hintText: 'Enter Passcode' 
}); 

//add labels and fields to window 
    win.add(entryCodeText); 
    win.add(debugText); 
    win.open(); 

while (exitCode == 0) { 
    // do stuff 
} // end of exitCode while loop 
// start of continuous program loop 
while (1) { 
    // if no event, just continue loop 
    // if event , execute several functions and continue with loop 
} // end of while(1) loop - runs as long as program runs 
//************************************************************************* 
entryCodeText.addEventListener("return", function(e) { 

    if (computeCode(entryCodeText.value)< 0) { 
     debugText.text = "failed computecode"; 
     exitCode = 0; 
     continue; 
    } else { 
     debugText.text = "passed computeCode()"; 
     exitCode = 1; 
     break; 
    } 
}); 
//continue with other logic on break and exitCode = 1 
//************************************************************ 
function computeCode(textValue) { 
    // do stuff to the textValue 
} 
+4

一般來說,沒有。爲什麼你需要一個無限循環而不是運行一些代碼來響應用戶輸入? – kabuko 2013-03-14 01:09:45

回答

0
while(true) 

應該使它永遠運行下去。

0

你可能使用keyup或keydown evt更好。

這就是說,如果你必須這樣做,你可以使用setTimeout函數。

就腳本執行而言,它始終運行最後(甚至在瀏覽器內部UI操作之後),因此可以防止UI被鎖定。

本例使用2個文本框。一旦第一個具有正確的值,它將進入內部循環。

<html> 
    <body> 
    UserName: <input type="text" id="txt" /><br> 
    Password: <input type="text" id="txt2" /> 


<script> 
    var txt = document.getElementById('txt'), 
     txt2 = document.getElementById('txt2'); 
    var loop, innerLoop; 
    (function loop(){ 
     setTimeout(function(){ 
      if(txt.value === 'name'){ 
      alert('correct username entered'); 
          //new loop 
       (function innerLoop(){ 
        setTimeout(function(){ 
         if(txt2.value === 'password') { 
          alert('correct password entered'); 
          return; 
         } 
         else setTimeout(innerLoop,0); 
        },0); 
       })(); 
       return; 
      } 
      else setTimeout(loop,0); 
     },0); 
    })(); 
</script> 

</body> 
</html> 

演示:http://jsfiddle.net/Vg5ND/

相關問題