javascript – 停止使用setTimeout运行的函数
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – 停止使用setTimeout运行的函数,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2035字,纯文字阅读大概需要3分钟。
内容图文
![javascript – 停止使用setTimeout运行的函数](/upload/InfoBanner/zyjiaocheng/709/0c67a6bf355b465fa8721e612dc9f07b.jpg)
我想停止使用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>
解决方法:
保存setTimeout的返回值,这是计时器的“句柄”,当您想要取消它时,请使用该值调用clearTimeout.
所以在你的代码中,你需要在适当的地方声明一个timerHandle变量,然后在这里设置它:
if (displayduration > 0)
timerHandle = setTimeout("hidetrail()", displayduration * 1000);
…然后创建一个按钮单击处理程序:
function cancelTimeoutOnClick() {
if (timerHandle) {
clearTimeout(timerHandle);
timerHandle = 0;
}
}
偏离主题:将字符串传递给setTimeout几乎绝不是最好的做法,这是一个隐式的eval.在您的情况下,只需传递函数引用:
if (displayduration > 0)
timerHandle = setTimeout(hidetrail, displayduration * 1000);
// ^--- Difference here (no quotes, no parentheses)
内容总结
以上是互联网集市为您收集整理的javascript – 停止使用setTimeout运行的函数全部内容,希望文章能够帮你解决javascript – 停止使用setTimeout运行的函数所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。