在一段时间后杀死一个

在一段时间后杀死一个

本文介绍了在一段时间后杀死一个 Javascript 进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果这是重复的,我深表歉意.

I apologize if this is a duplicate.

假设我有一个 JavaScript 函数,它调用 Web 服务来提取一些数据.我使用某种移动图形让用户知道它正在工作.成功检索后,我将图形更改为复选标记.这是我的代码:

Let's say I have a JavaScript function that calls a web service to pull some data. I use some kind of moving graphic to let the user know it's working. When it is successfully retrieved, I change the graphic to a check mark. Here's my code:

getData: function() {
    $("#button").attr("disabled", "true");

    var params = {
        doRefresh: false,
        method: '/GetData',
        onSuccess: new this.getDataCallback(this).callback,
        onFailure: new this.getDataFailed(this).callback,
        args: { text: $("#getData").val() }
    };

        WebService.invoke(params.method, params.onSuccess, params.onFailure, params.args);

}

我想要的是 5 分钟后,如果此进程仍未成功返回我的数据,则抛出异常,或者更好的是,运行我的函数 this.getDataFailed(this).callback.这对 JavaScript 似乎可行吗?我看过 setTimeout() 和 setInterval(),这些似乎只是延迟了脚本的执行,而我想从字面上超时"一个长时间运行的进程.有什么想法吗?

What I'd like is after 5 minutes, if this process still has not successfully returned my data, to throw an exception or, better yet, run my function this.getDataFailed(this).callback. Does this seem feasible with JavaScript? I've looked at setTimeout() and setInterval(), and these appear to just delay the execution of a script, whereas I want to literally "timeout" a long running process. Any ideas?

此外,我愿意接受任何批评/改进我的代码以实现此功能.

Also, I'm open to any criticism / improvements to my code that would allow for this functionality.

推荐答案

IE8 提供了一个 timeout 属性和 ontimeout 事件.然而,这些是非标准的.

IE8 offers a timeout property and ontimeout event. These are non-standard however.

我注意到您在一些示例代码中使用了 jQuery.jQuery 还为其 ajax() 属性支持 timeout 属性code> 方法将在达到超时限制后执行 error 回调.您可以使用 $.ajaxSetup() 方法来声明进行任何 ajax 调用之前的超时时间:

I noticed you're using jQuery in some of your example code. jQuery also supports a timeout property for its ajax() method which will execute the error callback after the timeout limit has been reached. You can use the $.ajaxSetup() method to declare the timeout before making any ajax calls:

$.ajaxSetup({
    timeout: 300000
});

如果您不使用 jQuery 发出请求,您可以滚动自己的超时代码:

If you're not using jQuery to make your requests you can roll your own timeout code:

var xhrTimeout;
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://blah.com/etc", true);
xhr.onreadystatechange = function ()
{
    if (xhr.readyState == 4)
        window.clearTimeout(xhrTimeout);
}
xhr.send();
xhrTimeout = window.setTimeout(function ()
{
    xhr.abort();
    failFunction();
}, 300000); // 5 mins

这篇关于在一段时间后杀死一个 Javascript 进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 04:29