2013-03-14 52 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/

相关问题