2014-06-30 49 views
0

http://jsfiddle.net/yhXum/4/在功能開始清除超時

當您按下啓動,該框移動到新位置,每兩秒鐘,但如果你一直按按鈕,:

setTimeout("random()", 2000); 

會疊加使箱子變得瘋狂。

我該如何使它在每次調用函數時都重置?

這是一個重複問題的原因是因爲我剛開始學習,我真的需要有人爲我做這件事,因爲我真的不知道如何實現類似問題的答案。

+1

通常認爲使用'setTimeout(random,2000)'而不是'setTimeout(「random()」,2000)''是很好的做法。 – soktinpk

回答

0

您可以隨時使用clearTimeout。不過,我的建議是隱藏啓動按鈕。如果你真的把它放在一個網站上,這對你的用戶也會更有意義。

http://jsfiddle.net/prankol57/g3heA/

STOP按鈕,你可以使用一個名爲interval變量來跟蹤間隔ID,後來清除。

function start() { 
    // Hide the start button 
    document.querySelector("#start").style.display = "none"; 
    document.querySelector("#stop").style.display = "block"; 
    random(); 
} 

function stop() { 
    clearTimeout(interval); 
    document.querySelector("#stop").style.display = "none"; 
    document.querySelector("#start").style.display = "block"; 
} 
0

使用clearTimeout

var myTimeout; 
function random() 
{ 
    clearTimeout(myTimeout); 
    x = Math.floor(Math.random() * (10 - 0 + 1)) + 0; 
    x = (x * 10); 
    y = Math.floor(Math.random() * (10 - 0 + 1)) + 0; 
    y = (y * 10); 

    document.getElementById("box").style.left = x + "px"; 
    document.getElementById("box").style.top = y + "px"; 

    myTimeout = setTimeout("random()", 2000);  
} 

http://jsfiddle.net/yhXum/5/

0

檢查這個 fiddle link沒有超時

var flag=true; 
function random() 
{ 
x = Math.floor(Math.random() * (10 - 0 + 1)) + 0; 
x = (x * 10); 
y = Math.floor(Math.random() * (10 - 0 + 1)) + 0; 
y = (y * 10); 

document.getElementById("box").style.left = x + "px"; 
document.getElementById("box").style.top = y + "px"; 
    if(flag){ 
     setTimeout(random, 2000); 
     flag=false; 
    } 

}