在功能开始时清除超时

时间:2014-06-30 14:20:34

标签: javascript settimeout

http://jsfiddle.net/yhXum/4/

当您按开始时,该框将每两秒移动一个新位置,但如果您一直按下该按钮,则:

setTimeout("random()", 2000);

会让盒子像疯了一样移动。

如何在每次调用函数时重置它?

这是一个重复问题的原因是因为我刚刚开始学习,我真的需要有人为我做这件事,因为我真的不知道如何从类似的问题中实现答案。 / p>

3 个答案:

答案 0 :(得分: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/

答案 1 :(得分: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;
    }

}

答案 2 :(得分:0)

您始终可以使用clearTimeout。但是,我的建议是隐藏开始按钮。如果你真的把它放在一个网站上,这对你的用户来说也会更有意义。

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

对于停止按钮,您可以使用名为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";
}