簡體   English   中英

使用setTimeout運行的停止功能

[英]stop function that run with setTimeout

我想停止使用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>
var foobarTimeout = setTimeout(foobar, 1000);

...

clearTimeout(foobarTimeout);

看到:
https://developer.mozilla.org/en/DOM/window.setTimeout
https://developer.mozilla.org/en/DOM/window.clearTimeout

保存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)

您使用超時>

var myTimeout = setTimeout(yourfunction);

然后您可以取消它>

clearTimeout(myTimeout);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM