停止超时功能

cmp*_*ger 1 javascript

在这段代码中:

$("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()});
});
Run Code Online (Sandbox Code Playgroud)

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

Poi*_*nty 5

将"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);});
});
Run Code Online (Sandbox Code Playgroud)

现在我实际上写的却完全不同了; 事实上,你在每次点击时都会添加一个冗余的"touchmove"处理程序.也许是这样的:

function setupAnchorClicks() {
  var timer = null;
  $("a").live("click", function(e) {
    e.preventDefault();

    timer = setTimeout(function() {
       // ...
    }, 1000);

  }).live("touchmove", function() {
    clearTimeout(timer);
  });
}

setupAnchorClicks();
Run Code Online (Sandbox Code Playgroud)