使用setTimeout运行的停止功能
我想停止使用setTimeout运行的函数,并且不显示跟随鼠标的图像.我想通过单击按钮做到这一点,怎么办? 我的代码:
I want stop my function that run with setTimeout and do not show image followed mouse. I want do that with button click, how do that? my code:
<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>
保存 setTimeout
,它是计时器的句柄",当您想要取消它时,请调用 clearTimeout
并带有该值.
Save the return value of setTimeout
, which is a "handle" for the timer, and when you want to cancel it, call clearTimeout
with that value.
因此,在您的代码中,您将在适当的位置声明一个timerHandle
变量,然后在此处进行设置:
So in your code, you'd declare a timerHandle
variable somewhere appropriate, then set it here:
if (displayduration > 0)
timerHandle = setTimeout("hidetrail()", displayduration * 1000);
...然后创建一个按钮click
处理程序:
...and then create a button click
handler:
function cancelTimeoutOnClick() {
if (timerHandle) {
clearTimeout(timerHandle);
timerHandle = 0;
}
}
离题:将字符串传递到setTimeout
几乎是最佳实践,这是隐式的eval
.就您而言,只需传递函数引用即可:
Off-topic: It's almost never best practice to pass strings into setTimeout
, that's an implicit eval
. In your case, just pass the function reference:
if (displayduration > 0)
timerHandle = setTimeout(hidetrail, displayduration * 1000);
// ^--- Difference here (no quotes, no parentheses)