简体   繁体   English

SetTimeout无法在on鼠标按下/ touchstart功能上执行

[英]SetTimeout not executing for on mousedown/touchstart function

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

Can anyone explain why this doesn't work? 谁能解释为什么这行不通? (Running Chromium on Linux) (在Linux上运行Chromium)

I'm trying to only execute the alertbox when the button is down for 2s, if it's not then to clear the timeout function. 我试图仅在按钮按下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>

That's not how clearTimeout works. 这不是clearTimeout工作方式。 You need to pass it the value that setTimeout returns. 您需要将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.
});

And you probably want to wrap this in a jQuery page ready callback so the script can be anywhere on the page: 您可能希望将其包装在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);
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM