2011-04-26 61 views
2

我想停止使用setTimeout運行的函數,並且不顯示隨鼠標顯示的圖像。我想用按鈕點擊來做,那是怎麼回事? 我的代碼:使用setTimeout運行的stop函數

<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> 
+0

在發佈的代碼中,您不執行t因爲displayduration爲0,所以超時。另外我建議你改變'setTimeout(「hidetrail()」,displayduration * 1000);''someVar = setTimeout(hidetrail,displayduration * 1000);'someVar是在哪裏定義的,去實現它。刪除引號會刪除隱藏的_eval_,這被認爲是邪惡的 – mplungjan 2011-04-26 06:21:12

回答

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) 
0

您使用超時喜歡>

var myTimeout = setTimeout(yourfunction); 

,然後你可以取消它>

clearTimeout(myTimeout); 
0

對於角度的用戶,如果使用NG - 例如更改:

//declare your scope var outside your function 
$scope.myVar; 

//the first thing you do is stop the previous timeout execution and then declare a new one (pretty friggin' cool and this makes me love angular more) 
$scope.myCustomFunction = function() { 
     clearTimeout($scope.myVar); 
     $scope.myVar = $timeout(function() { alert($scope.myVar); }, 2000); 
}