2016-08-24 72 views
1

我加載位於我的服務器上用這種簡單的方法.txt文件:的Javascript文本文件加載延遲

function getFileFromServer(url, doneCallback) 
{ 
console.time("getFileFromServer"); 
var xhr; 

xhr = new XMLHttpRequest(); 
xhr.onreadystatechange = handleStateChange; 
xhr.open("GET", url, true); 
xhr.send(); 

function handleStateChange() { 
    if (xhr.readyState === 4) { 
     doneCallback(xhr.status == 200 ? xhr.responseText : null); 
    } 
} 
console.timeEnd("getFileFromServer"); 
} 

我使用它,在這個簡單的方式,因此這個帖子:Reading a txt file from Server, writing it to website

function loadFile(url) { 
    console.time("loadFile"); 
    getFileFromServer(url, function(text) { 
    if (text === null) { 
     console.log("error-loading-file"); 
    } 
    else { 
     console.timeEnd("loadFile"); 
     doStuff(text); 
    } 
}); 

正如你所看到的,我已經把console.time記錄下來了。下面是瀏覽器控制檯答案:

getFileFromServer:1.744ms

的loadFile:18114.871ms

我不是一個JavaScript專家,我可以找出唯一解釋的時間差是參數傳遞(值與C++中的參考)。有人可以解釋我在時間上的差異嗎?

+0

這是因爲ajax調用的'async'性質。 http://stackoverflow.com/questions/11233633/understanding-asynchronous-code-in-laymans-terms – shakib

回答

1

getFileFromServer完成得非常快的原因是沒有真正的處理過程。該功能不會等待,直到請求從服務器返回,但僅在其註冊回調函數。這意味着它花了1.744ms到發送的請求,沒有更多。

loadFile函數測量發送請求和實際獲得響應之間的時間。這是不同的。