[英]javascript: break a recursive call after a time duration
I am trying to execute a recursive AJAX call to handle one of the functionality in my application. 我试图执行一个递归AJAX调用来处理我的应用程序中的功能之一。 The scenario is as below:
场景如下:
I want to make sure that if the server returns String B as the response for more than two minutes, the recursive execution should stop and an error message should be displayed to the user. 我想确保,如果服务器在超过两分钟的时间内返回字符串B作为响应,则递归执行应该停止并且应该向用户显示错误消息。
Can someone suggest an appropriate way for doing this? 有人可以建议这样做的合适方法吗?
Here is the sample JS code. 这是示例JS代码。 We are using ExtJS:
我们正在使用ExtJS:
function process()
{
Ext.Ajax.request({
url : "ABC.action",
form: 'formname',
params:{
method : "Serversidehandler",
},
success : processSuccess,
failure : processFail
});
}
function processSuccess(request)
{
if(request.responseText != null)
{
var responseJSON = Ext.decode(request.responseText);
var response = responseJSON.response;
if(response != null)
{
if(response == "A")
{
// do something
}
else if(response == "B")
{
process() // main method called again
}
}
}
}
Try the below given code, setTimeout works fine with the delays. 尝试以下给定的代码,setTimeout可以很好地处理延迟。
Kindly specify the requirement more clearly. 请更清楚地指定要求。
function process()
{
Ext.Ajax.request({
url : "ABC.action",
form: 'formname',
params:{
method : "Serversidehandler",
},
success : processSuccess,
failure : processFail
});
}
function processSuccess(request)
{
if(request.responseText != null)
{
var responseJSON = Ext.decode(request.responseText);
var response = responseJSON.response;
if(response != null)
{
if(response == "A")
{
// do something
}
else if(response == "B")
{
window.setTimeout(process(), 2000); // main method called again
}
}
}
}
var startTime = (new Date).getTime();
function process() {
Ext.Ajax.request({
url: "ABC.action",
form: 'formname',
params: {
method: "Serversidehandler",
},
success: processSuccess,
failure: processFail
});
}
function processSuccess(request) {
var elapsedTime = 0;
if (request.responseText != null) {
var responseJSON = Ext.decode(request.responseText);
var response = responseJSON.response;
if (response != null) {
if (response == "A") {
// do something
}
else if (response == "B") {
elapsedTime = (new Date().getTime()) - startTime;
if (elapsedTime <= 2000) {
process() // main method called again
};
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.