2014-06-30 48 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; 
    } 

}