問題描述
您好,我目前正在發(fā)出 xmhhttp 請求,但該網(wǎng)站需要一些時(shí)間來加載,所以我只得到 ReadyState = 3 和狀態(tài) = 200.所以我需要等到 readystate = 4 的東西,但我想限制如果readystate = 4,它每秒只檢查一次,否則什么也不做.
Hi im currently making a xmhhttp request, but the site takes some time to load, so I only get the ReadyState = 3 and status = 200. So I need something that waits until the readystate = 4, but I want to limit this function so that it only checks once a second if the readystate = 4, else do nothing.
這樣的延遲函數(shù)長什么樣子?
How can such a delay function look like?
if (xmlhttp.readyState==4 && xmlhttp.status==200)//Add the delay here so that the else doesn't occur
{
var txt=xmlhttp.responseText;
.....
else {
document.write("status: " + xmlhttp.readyState + " " + xmlhttp.status);
}
推薦答案
我們可以寫一個(gè)函數(shù)來檢查你的 xmlhttp-object 的狀態(tài):
We can write a function for checking the state of your xmlhttp-object:
var checkState = function(xmlhttp, callback) {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
callback(whatever, arguments, that, you, want, to, send);
} else {
// Check back again 1 sec later
setTimeout(checkState, 1000);
}
};
那么你可以這樣使用它:
Then you can use it like this:
checkState(xmlhttp, function(whatever, arguments, you, need) {
// the code here will be run when the readyState is 4 and the status is 200
});
不過有兩件事:
- 無論 readyState 是什么,checkState 函數(shù)都會(huì)返回,因此請確保您只在回調(diào)中執(zhí)行依賴于它的操作,而不是之后.
- 如果 readyState 和 status 從來沒有得到你想要的值,那么你就不走運(yùn)了(但你可以擴(kuò)展函數(shù)以接受第二個(gè)回調(diào)來處理超時(shí)情況).
這篇關(guān)于需要一個(gè)延遲函數(shù)javascript的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!