[英]Javascript synchronous timeout in while loop
我正在尝试在执行AJAX请求时伪造同步JavaScript。 我有一个getPagePath(id)
函数,它需要通过为页面ID提供页面ID来获取页面的页面路径,它通过Web API接收数据。 我认为这很简单,只需对服务器执行ajax请求并接收页面路径。 但是发生了什么:在请求页面路径时,我的代码继续运行并返回一个空的var,之后ajax调用结束,但是迟到了。
我知道我的解释并不多,所以这里是我的代码:
var getPagePath = function() {
// Function to check if this.pagePath is set.
var pagePathReady = function() {
console.log('PAGEPATH: CHECKING');
if (this.pagePath && this.pagePath != null) {
return true;
} else {
return false;
}
};
if (!pagePathReady()) {
// No pagePath defined so lets set it.
this._setPagePath();
while (!pagePathReady())
{
// Not yet defined, check again..
// *** The problem ***
// This while loop is running insanely fast making the browser crash.
// How can I make this wile loop pause for 1 sec?
// *******************
console.log('PAGEPATH: NOT READY -> CHECK AGAIN');
}
// READY
console.log('PAGEPATH: READY -> VALUE: ' + this.pagePath);
return this.pagePath;
} else {
return this.pagePath;
}
};
var _setPagePath = function() {
if (!this.pagePathRequestFired) {
this.pagePathRequestFired = true;
// Fire request.
system.url(
this.getNodeId(),
function(url) {
// Request ready, set pagePath.
this.pagePath = url;
this.pagePathRequestFired = false;
},
this
);
} else {
// Call already running..
}
};
我在更多解释性评论中设置了问题。
提前致谢!
而不是轮询pagePath
(似乎不需要恕我直言)为什么不在_setPagePath准备就绪时执行回调? 如果要伪造同步请求,只需将加载微调器作为叠加显示给用户,从而禁用UI。
如果确实需要,可以使ajax调用同步。
xmlhttp.open("GET", "url", false);
注意第3个参数。
但是,我认为您只需要编写代码来练习事件/回调概念。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.