首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SetTimeout不执行on /touchstart函数

SetTimeout不执行on /touchstart函数
EN

Stack Overflow用户
提问于 2013-12-23 20:39:26
回答 1查看 1K关注 0票数 0

小提琴- http://jsbin.com/AYeFEHi/1/edit

有人能解释一下为什么这不管用吗?(在Linux上运行铬)

当按钮关闭2s时,我尝试只执行alertbox,如果不是为了清除超时函数的话。

代码语言:javascript
复制
<!DOCTYPE html>
<html>
<head>
<title>Testing onmousedown setTimeout alert</title>
<meta charset='utf-8'>
<meta name='viewport' content='initial-scale=1.0'>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.9.1.min.js'></script>
<script type='text/javascript'>
function call() {
  alert('Hello World!');
}

$("#alertme").on('mousedown touchstart', function() {
  setTimeout(call, 2000);
});

$("#alertme").on('mouseup touchend', function() {
  clearTimeout(call, 0);
});
</script>
</head>
<body>
  <button id="alertme">Alert me</button>
</body>
</html>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-12-23 20:42:43

这不是clearTimeout的工作方式。您需要将setTimeout返回的值传递给它。

代码语言:javascript
复制
function call() {
  alert('Hello World!');
}

var callTimeout = null; // hold onto the identifier for the timeout

$("#alertme").on('mousedown touchstart', function() {
  callTimeout = setTimeout(call, 2000);
});

$("#alertme").on('mouseup touchend', function() {
  clearTimeout(callTimeout); // clear the timeout identifier we saved.
});

您可能希望将其包装在jQuery页面中,这样脚本就可以在页面上的任何位置:

代码语言:javascript
复制
$(function() {
  var call = function() {
    alert('Hello World!');
  }

  var callTimeout = null;

  $("#alertme").on('mousedown touchstart', function() {
    callTimeout = setTimeout(call, 2000);
  });

  $("#alertme").on('mouseup touchend', function() {
    clearTimeout(callTimeout);
  });
});
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20750857

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档