2012-12-06 72 views
1

我對JavaScript很陌生,似乎無法得到setTimeout命令來執行任何操作。我知道這個問題之前已經被問過很多次了,但是我花了最近兩個小時看過它以前的所有案例,但它仍然不適合我。這是我目前得到的:JavaScript settimeout函數的問題

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

    var i = 0; 
    function aloop() { 
     document.write(i); 
     i++; 
    } 

    function afunction() { 
     if (i <= 12) { 
      setTimeout(aloop(), 1000); 
      afunction(); 
     } 
    } 

    </script> 

    <form> 
    <input type=submit value="Click me!" onClick="afunction()"> 
</html> 

有誰能告訴我該怎麼做才能做到這一點嗎?

+0

除了答案,考慮使用常規'for'循環。 –

回答

4

將函數傳遞給setTimeout,而不是函數調用的返回值。

setTimeout(aloop,1000); 
1

的問題是你調用你的函數,而不是排隊你的函數。

setTimeout(aloop, 1000)setTimeout(aloop(), 1000);

1

你沒有描述什麼是不行的,但我會假設你希望i在1000個毫秒間隔被寫入。

這樣做:

<html> 
<!-- you're missing your head tags --> 

<head> 
    <title> my page </title> 

    <script type="text/javascript"> 
    var i=0; 
    function aloop() { 
      // don't use document.write after the DOM is loaded 
     document.body.innerHTML = i; 
     i++; 
     afunction(); // do the next call here 
    } 
    function afunction() { 
     if (i<=12) { 
       //  v---pass the function, don't call 
      setTimeout(aloop,1000); 

     // afunction(); // remove this because it'll call it immediately 
     } 
    } 
    </script> 
</head> 

<!-- you're missing your body tags --> 
<body> 
    <form> 
     <input type=submit value="Click me!" onClick="afunction()"> 
    </form> <!-- you're missing your closing form tag --> 
</body> 
</html> 
+0

感謝大家的全力幫助。它正在按照我現在所需的方式工作。 – user1883633

+0

不客氣。 –