javascript - SetTimeout 未针对 mousedown/touchstart 函数执行

标签 javascript jquery

fiddle - http://jsbin.com/AYeFEHi/1/edit

谁能解释一下为什么这不起作用? (在 Linux 上运行 Chromium)

我尝试仅在按钮按下 2 秒时执行警报框,如果不是,则清除超时功能。

<!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>

最佳答案

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

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 页面就绪回调中,以便脚本可以位于页面上的任何位置:

$(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);
  });
});

关于javascript - SetTimeout 未针对 mousedown/touchstart 函数执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20750857/

相关文章:

javascript - 在 Atom 包中获取整个树守护者解析树

jquery - 使用开始标签与自结束标签创建空元素

jquery - jquery 中的 'first-child' 选择器问题

javascript - 无法使用 jQuery 选择 div(动态生成)

javascript - Jquery 如何停止追加上一个元素

javascript - jQuery:瞄准类(class)前 3 名

javascript - 输入验证 - 如何允许退格键在我的方法中工作

javascript - Ember 应用程序未使用 Ember 数据发布到服务器

javascript - 纯静态 html 文件与内容通过 JS 和 noSQL 加载的静态 html 文件之间的性能

javascript - Express - 获取正在运行的域名服务器