[英]making asynchronous calls with jquery
我有一個名為checkStatus(x)
的函數,其中x是ID。 我如何異步調用此函數n次? 不必依靠彼此來完成並開始另一個?
我正在使用jQuery
編輯:
我不確定是否使用了正確的術語,但這就是我想要的。 我有一個ID列表,並且遍歷一個列表,我想為每個ID執行此功能。
但是我不想等待一個ID完成,然后在另一個ID上執行此功能。 是否可以同時執行此功能?
JavaScript引擎是單線程的,這意味着一次只能執行一段代碼。 異步功能(AJAX, 超時 / 時間間隔 )導致不同的代碼塊按順序運行,而不是並行運行(即,您永遠不會在Javascript中使用多個處理器內核)。
正如其他人所建議的那樣,生成異步(非阻塞)代碼的最簡單方法是使用setTimeout
( 我強烈建議不要使用setInterval
),但是這樣做沒有任何性能上的好處。 通過允許瀏覽器的其他任務(例如頁面重繪和用戶輸入)運行,這可以確保瀏覽器在JS緩慢計算期間不會“掛起”。 它實際上並不會提高這些計算的速度(實際上,由於超時的少量額外開銷,它會稍微減慢它們的速度)。
它可以創建一個使用Javascript中單獨的線程網絡工作者 ,但他們的能力是有限的(例如,他們不能改變DOM)和他們還沒有支持IE 。
使用“遞歸” setTimeout
調用的長時間運行的非阻塞任務的示例:
function getStarted(elements) {
// this function must be inside the outer function
// so that `i` (below) can be accessed via a closure
function processElement() {
// do work on elements[i] here
// or pass it to another function
// this continues only if we haven't hit the end of the array,
// like the second and third clauses of a `for` loop
if (++i < elements.length) {
setTimeout(processElement, 0);
}
}
// don't bother with empty arrays
if (elements.length) {
// the same `i` is used each time processElement runs
// and acts just like a `for` loop index
var i = 0;
// optional: make a copy of the array so that it
// doesn't get modified while we're working
elements = elements.slice();
// even a zero-millisecond "delay" gives the browser the
// opportunity to run other code
setTimeout(processElement, 0);
}
}
使用setTimeout
或setInterval
函數。
setTimeout(function(){checkStatus(x);}, 100);
setTimeout(function(){checkStatus(x);}, 200);
setTimeout(function(){checkStatus(x);}, 300);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.