2012-01-11 90 views
0

我試圖在屏幕上逐漸顯示文本(如字幕)。例如H ..他..地獄..你好。當我在VS2010中進行調試時,它正在工作!但是當它實際運行時,它會立即顯示整個句子。函數調用函數WEIRD結果

我在每個字母之間做了一定的「延遲」約3秒,所以它會假設需要一段時間,但實際上它會立即顯示一切。

誰是解決這個謎的天才? (請不要給我建議如何創建marquee效果,這不再是問題,現在它只是我和javascript之間的WAR!)我假設它在從函數調用函數時與同步有關?

感謝任何人會幫助我恢復理智。

您可以下載代碼從這裏(VS項目): http://pcgroup.co.il/downloads/misc/function_from_function.zip

或查看在這裏:

 <body> 
     <script type="text/javascript"> 

//trying to display this source sentence letter by letter: 
     var source = "hi javascript why are you being such a pain"; 
     var target = ""; 
     var pos = 0; 
     var mayGoOn = false; 

    //this function calls another function which suppose to "build" the sentence increasing index using the global var pos (it's even working when following it in debug) 
    function textticker() { 
       if (pos < source.length) { 
        flash(); 

        if (mayGoOn == true) { 
         pos++; 
         mayGoOn = false; 
         document.write(target); 

         textticker(); 
        } 
       } 
      } 
      function flash() { 

    //I tried to put returns everywhere assuming that this may solve it probably one of them in not necessary but it doesn't solve it 
       if (mayGoOn == true) { return; } 

       while (true) { 
        var d = new Date(); 
        if (d.getSeconds() % 3 == 0) { 
         //alert('this suppose to happen only in about every 3 seconds'); 
         target = source.substring(0, pos); 
         mayGoOn = true; 
         return; 
        } 
       } 
      } 


      textticker(); 


     </script> 
+1

你應該看看'setTimeout'或'setInterval'功能。 – 2012-01-11 10:35:12

+1

這不是你在同步上下文中做延遲的方式。查找'setTimeout'。 – 2012-01-11 10:35:17

+1

除了塞爾吉奧的回答,這不起作用的原因是循環每秒發生一次以上,所以d.getSeconds()%3 == 0將每3秒成千上萬次。它在調試中起作用的原因是你大量減慢了執行速度。爲了讓它工作,你必須檢查你和上次不一樣。這也將是UI阻塞,所以不是一個好主意。 – mattmanser 2012-01-11 10:42:47

回答

0

你明明做錯了。看看這個。

var message = "Hello World!"; 

function print(msg, idx) { 
    if(!idx) { 
    idx = 0; 
    } 

    $('#hello').html(msg.substring(0, idx)); 

    if(idx < msg.length) { 
    setTimeout(function() { print(msg, idx + 1) }, 200); 
    } 
} 

print(message); 

演示:http://jsbin.com/evehus