我看到這裏有很多關於請求JavaScript睡眠函數的線程,我知道它只能使用setTimeout
和setInterval
來完成。如何在需要休眠功能時重構JavaScript代碼?
我做一些使用greasemonkey的用戶腳本,並編寫了一個加載大量頁面並從中計算出一些內容的腳本。它可以工作,但我不想過快地請求頁面。
var html0=syncGet(url0); // custom function for sync ajax call.
// fill the something array
for(var i=0;i<something.length;i++)
{
// calculate url1,url2 using the array and the i variable
// do something with lots of local variables
var html1=syncGet(url1);
// I would put a sleep here.
// do something with the results
var html2=syncGet(url2);
// I would put a sleep here.
// do something with the results
// get url3 from the page loaded from url2
var html3=syncGet(url3);
// I would put a sleep here.
// do something with the results
}
// use the result of the for loop and lots of code will follow...
實際的代碼有點複雜,比這個更長。
我爲不存在的睡眠函數哭泣(並理解爲什麼它是不可能的)如何重構這個使用setTimeout,setInterval函數並保持它的可讀性(和工作)呢?
,您可以在setTimeout的改變「1」到別的東西.. – dwarfy 2011-04-29 08:51:16