停止超时函数



在此代码:

$("a").live("click", function(e) {
    e.preventDefault();
    setTimeout(function () {
        $.get(
            "someOtherUrl",
            {someVariable: "someValue"},
            function(result) {
                $(".result").html(render(result));
            }
        );
    }, 1000);
    $('a').live("touchmove", function(e) {clearTimeout()});
});

我想在用户在屏幕上移动手指时停止超时。问题是clearartimeout()不起作用,因为它没有链接到超时。我该如何命名超时并快速清除它?我用的方法对吗?

将"setTimeout()"的返回值保存在一个变量中,然后将该值传递给"clearTimeout()"来清除它。

$("a").live("click", function(e) {
    e.preventDefault();
    var t = setTimeout(function () {
               $.get(
                     "someOtherUrl",
                     {someVariable: "someValue"},
                     function(result) {
                     $(".result").html(render(result));
                     }
                     );
    }, 1000);
    $('a').live("touchmove", function(e) {clearTimeout(t);});
});

我想用不同的方式来写;实际上,您在每次点击上都添加了一个冗余的"touchmove"处理程序。也许像这样:

function setupAnchorClicks() {
  var timer = null;
  $("a").live("click", function(e) {
    e.preventDefault();
    timer = setTimeout(function() {
       // ...
    }, 1000);
  }).live("touchmove", function() {
    clearTimeout(timer);
  });
}
setupAnchorClicks();

您必须保存从setTimeout接收到的句柄(它是一个普通整数),然后将其作为参数传递给clearartimeout。

var functionToCancel = function() {console.log("hello");}
var timeoutHandle = setTimeout(functionToCancel, 1000);
clearTimeout(timeoutHandle);

最新更新