【问题标题】:timeout for function (jQuery)函数超时(jQuery)
【发布时间】:2011-03-09 09:55:24
【问题描述】:
function getNames(){
    // some code
}

这个功能可以在一秒钟内完成,但有时它会在无限时间内冻结自身和页面上的html块(ajax inside)。

我想对这个功能有时间限制。如果它没有在十秒内完成,则中止它。

如何做到这一点?

【问题讨论】:

  • 您是否将“async:true”作为 ajax 参数?
  • 如果我们知道 //Some Code 是什么可能会有所帮助...
  • 如果//某些代码有时可能需要很长时间(例如等待来自慢速服务器的大量信息),您可能会考虑使用网络工作者。这样您就不会在主页中被阻止。
  • @tiagoboldt 我不擅长javascript,你能给出示例代码吗?

标签: javascript jquery html function timeout


【解决方案1】:

使用 jQuery 1.5 的 deferred promises 真的很容易。

以下示例创建一个 Deferred 并将两个基于计时器的函数设置为在随机间隔后 resolvereject Deferred。无论哪个先触发“获胜”,都会调用其中一个回调。第二次超时无效,因为从第一次超时操作开始,延迟已经完成(处于已解决或拒绝状态)。

// Create a Deferred and return its Promise
function asyncEvent() {
    var dfd = new jQuery.Deferred();
    setTimeout(function() {
        dfd.resolve('hurray');
    }, Math.floor(Math.random() * 1500));
    setTimeout(function() {
        dfd.reject('sorry');
    }, Math.floor(Math.random() * 1500));
    return dfd.promise();
}

// Attach a done and fail handler for the asyncEvent
$.when( asyncEvent() ).then(
    function(status) {
        alert( status + ', things are going well' );
    },
    function(status) {
        alert( status + ', you fail this time' );
    }
);

您可以轻松修改此示例以满足您的需要:

// Create a Deferred and return its Promise
function asyncEvent() {
    var dfd = new jQuery.Deferred();

    // Your asynchronous code goes here

    // When the asynchronous code is completed, resolve the Deferred:
    dfd.resolve('success');

    setTimeout(function() {
        dfd.reject('sorry');
    }, 10000); // 10 seconds
    return dfd.promise();
}

// Attach a done and fail handler for the asyncEvent
$.when( asyncEvent() ).then(
    function(status) {
        alert( status + ', things are going well' );
    },
    function(status) {
        alert( status + ', you fail this time' );
    }
);

【讨论】:

  • 如何在我的函数中使用它?我应该在哪里粘贴代码。拒绝/解决 - 状态文本?
  • @Happy Resolve the Deferred when the asynchronous code is done, e.g. dfd.resolve('success');。 (也将此添加到答案中。)您应该允许 getNames 接受执行此操作的回调函数。
  • 再次抱歉,如何与 getNames() 一起使用?
  • @Happy:我刚刚在之前的评论中告诉过你。
【解决方案2】:

如果是函数本身被淘汰,只需设置一个计时器,如果它超过了您的最大时间段,请设置 returnthrow

另一方面,如果延迟是由未返回的 AJAX 请求引起的,并且您正在使用 $.ajax(),则始终可以设置 timeout 设置。它应该终止请求。请注意,您需要避免依赖success 回调,因为只有在请求成功时才会调用它。相反,使用complete 回调来监视失败。它会告诉您是否发生错误。根据文档,这在 1.4 及更高版本中可用。我不确定 pre-1.4,但我认为它也适用于 1.3。

【讨论】:

    【解决方案3】:

    如上所述,如果某些代码有时可能需要很长时间(例如等待来自慢速服务器的大量信息),您可以使用 Web Workers。这将允许后台处理而不锁定主页。请注意,并非所有浏览器都支持它。

    你可以找到一个不错的介绍here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-24
      • 1970-01-01
      • 1970-01-01
      • 2017-06-25
      • 2016-03-15
      • 2017-10-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多