weixin_33730836 2016-04-14 16:15 采纳率: 0%
浏览 16

杀死重复的AJAX请求

I have an AJAX request that looks like this:

var statistics = "link-to-a-JSONP";

function team_stats(json) {
   alert(json);
}

(function stats() {
        $.ajax({
            type: 'GET',
            url: statistics + '?callback=jsonp',
            crossDomain: true,
            dataType: 'jsonp',
            jsonpCallback: 'team_stats',
            jsonp: 'callback',
            data: {},
            success: function(data) {
              var test += '<div>' + data + '</div>';
              $(".content").append(test);

              /* a close button that closes the tab and kills the request */
              $("#closeStats").on("click", function() {
                    stats.abort();
                });
            },
            complete: function() {
              setTimeout(stats, 15000);
            }
       });
})();

This works great and the request repeats itself every 15 seconds. Now, I want to kill the request when I click a certain button (as shown). The compiler says that the fragment stats.abort() is not a function and continues the loop.

Any ideas?

  • 写回答

1条回答 默认 最新

  • weixin_33735676 2016-04-14 16:45
    关注

    You are calling abort on a function. Functions do not have abort.

    You want to kill the setTimeout. So you need to hold a reference to the timer.

    (function () {
        var timer;
        function foo () {
            console.log(new Date());
            timer = window.setTimeout(foo,1000);  //<-- store a reference to the timeout
        }
    
        function killTimer() {
            if (timer) window.clearTimeout(timer);
        }
    
    }());
    

    If you want to also abort an active Ajax request, you need to hold a reference to that too.

    xhr = $.ajax(...);
    ...
    xhr.abort();
    
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?