停止使用setTimeout运行的函数

时间:2011-04-26 06:12:36

标签: javascript

我希望停止使用setTimeout运行的函数,并且不要在鼠标后面显示图像。我想用按钮点击这样做,怎么做? 我的代码:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<script type="text/javascript">
    var trailimage = ["test.gif", 100, 99];
    var offsetfrommouse = [-25, -25];
    var displayduration = 0;
    function truebody() {
        return (!window.opera && document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body;
    }
    function hidetrail() {
        var x = document.getElementById("trailimageid").style;
        x.visibility = "hidden";
        document.onmousemove = "";
    }
    function followmouse(e) {
        var xcoord = offsetfrommouse[0];
        var ycoord = offsetfrommouse[1];
        if (typeof e != "undefined") {
            xcoord += e.pageX;
            ycoord += e.pageY;
        }
        else if (typeof window.event != "undefined") {
            xcoord += truebody().scrollLeft + event.clientX;
            ycoord += truebody().scrollTop + event.clientY;
        }
        var x = document.getElementById("trailimageid").style;
        x.left = xcoord + "px";
        x.top = ycoord + "px";            
    }

        alert("obj_selected = true");
        document.onmousemove = followmouse;
        if (displayduration > 0)
            setTimeout("hidetrail()", displayduration * 1000);

</script>
</head>
<body>
<form id="form1" runat="server">

    <img alt="" id="trailimageid" src="Pictures/sides/sides-not-clicked.gif" border="0" style="position: absolute; visibility: visible; left: 0px;
    top: 0px; width: 50px; height: 50px"/>

</form>
 </body>
</html>

3 个答案:

答案 0 :(得分:4)

var foobarTimeout = setTimeout(foobar, 1000);

...

clearTimeout(foobarTimeout);

请参阅:
https://developer.mozilla.org/en/DOM/window.setTimeout
https://developer.mozilla.org/en/DOM/window.clearTimeout

答案 1 :(得分:1)

保存setTimeout的返回值,这是计时器的“句柄”,当您想取消它时,请使用该值调用clearTimeout

因此,在您的代码中,您需要在适当的位置声明timerHandle变量,然后在此处设置:

if (displayduration > 0)
    timerHandle = setTimeout("hidetrail()", displayduration * 1000);

...然后创建一个按钮click处理程序:

function cancelTimeoutOnClick() {
    if (timerHandle) {
        clearTimeout(timerHandle);
        timerHandle = 0;
    }
}

偏离主题:将字符串传递给setTimeout几乎绝不是最佳做法,这是隐式eval。在您的情况下,只需传递函数引用:

if (displayduration > 0)
    timerHandle = setTimeout(hidetrail, displayduration * 1000);
                          // ^--- Difference here (no quotes, no parentheses)

答案 2 :(得分:0)

你使用像&gt;

这样的超时
var myTimeout = setTimeout(yourfunction);

然后你可以取消它&gt;

clearTimeout(myTimeout);