[JavaScript] Run to Completion and the Event Loop

The JavaScript you write runs on a single thread, which avoids complications found in otherlanguages that share memory between threads. But if JavaScript is single-threaded, where are theasync tasks and callbacks run?

youwere just told that JavaScript is single-threaded. Here’s the distinction: the JavaScript code you write(js代碼是單線程的鹿霸,同一時間只有一段代碼在執(zhí)行蒂胞。但是拆撼,js運行環(huán)境不是單線程的) all runs on a single thread, but the code that implements the async tasksis not part of that JavaScript and is free to runin a separate thread.

Once the task completes the result needs to be provided to the JavaScript thread. At this point the callback is placed in a queue(當異步任務完成后署隘,回調函數(shù)才會被放到任務隊列中殷勘。而注冊回調函數(shù)時况鸣,并不會把回調放到任務隊列中。). A multithreaded language might interrupt whatever code was
currently executing to provide the results, but in JavaScript these interruptions are forbidden.Instead there is a run-to-completion rule, which means that your code runs without interruptionuntil it passes control back to the host environment by returning from the function that the hostinitially called. At that point the callback can be removed from the queue and invoked.

All other threads communicate with your code by placing items on the queue. They are not
permitted to manipulate any other memory accessible to JavaScript.

After the callback is added to the queue, there is no guarantee how long it will have to wait(異步任務執(zhí)行完后的回調已經在任務隊列中了饵较,但是主線程不執(zhí)行完,就不會從任務隊列中取回調遭赂,該回調前的回調沒有執(zhí)行完循诉,也不會取這個回調。). Howlong it takes the current code to run to completion and what else is in the queue controls the time.The queue can contain things such as mouse clicks, keystrokes, and callbacks for other async tasks.The JavaScript runtime simply continues in an endless cycle of pulling an item off the queue if one is available(從隊列先取出一個執(zhí)行完再绕菜), running the code that the item triggers, and then checking the queue again. This cycleis known as the event loop.

注:關于XMLHttpRequest與Promise

(1)XMLHttpRequest

var async = true;
var xhr = new XMLHttpRequest();
xhr.open('get', 'data.json', async);
xhr.send();

xhr.addEventListener('load', listener);

因為xhr.send是異步任務茄猫,
所以不等帶執(zhí)行完狈蚤,就立即執(zhí)行主線程的xhr.addEventListener以及后面的代碼。
等異步任務執(zhí)行完划纽,listener會放到任務隊列中脆侮。
主線程執(zhí)行完后,會從任務隊列中取回調函數(shù)勇劣,
當取到listener時靖避,這個回調就觸發(fā)了。

但是比默,如果改成一下方式幻捏,就不能觸發(fā)回調了。

var async = true;
var xhr = new XMLHttpRequest();
xhr.open('get', 'data.json', async);
xhr.send();    //假設ajax 5s內一定會返回命咐。

setTimeout(function(){
    xhr.addEventListener('load', listener);
},5000);

等ajax響應完再addEventListener是沒有用的篡九,
因為ajax響應完,發(fā)現(xiàn)并沒有注冊回調醋奠,就不會把回調放到任務隊列中榛臼。
5000后注冊的回調,只有在下次send時窜司,才會用到讽坏。

(2)Promise

var p=new Promise(function(resolve,reject){
    alert(1);
    resolve(0);
});

alert(2);

p.then(function(v){
    alert(v); //0
});

alert(3);
執(zhí)行順序:1 2 3 0

我們看到,
<u></u>new Promise的參數(shù)是同步函數(shù)例证,會立即執(zhí)行路呜,才會執(zhí)行后面的alert(2)
<u></u>p.then在Promise resolve后仍然可以注冊,并立即放到任務隊列中织咧。
<u></u>p.then注冊的回調是異步的胀葱,放到任務隊列但是不會馬上執(zhí)行,等主線程執(zhí)行完才執(zhí)行笙蒙。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末抵屿,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子捅位,更是在濱河造成了極大的恐慌轧葛,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,122評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件艇搀,死亡現(xiàn)場離奇詭異尿扯,居然都是意外死亡,警方通過查閱死者的電腦和手機焰雕,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,070評論 3 395
  • 文/潘曉璐 我一進店門衷笋,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人矩屁,你說我怎么就攤上這事辟宗【粽裕” “怎么了?”我有些...
    開封第一講書人閱讀 164,491評論 0 354
  • 文/不壞的土叔 我叫張陵泊脐,是天一觀的道長空幻。 經常有香客問我,道長容客,這世上最難降的妖魔是什么秕铛? 我笑而不...
    開封第一講書人閱讀 58,636評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮耘柱,結果婚禮上如捅,老公的妹妹穿的比我還像新娘。我一直安慰自己调煎,他們只是感情好镜遣,可當我...
    茶點故事閱讀 67,676評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著士袄,像睡著了一般悲关。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上娄柳,一...
    開封第一講書人閱讀 51,541評論 1 305
  • 那天寓辱,我揣著相機與錄音,去河邊找鬼赤拒。 笑死秫筏,一個胖子當著我的面吹牛,可吹牛的內容都是我干的挎挖。 我是一名探鬼主播这敬,決...
    沈念sama閱讀 40,292評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼蕉朵!你這毒婦竟也來了崔涂?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 39,211評論 0 276
  • 序言:老撾萬榮一對情侶失蹤始衅,失蹤者是張志新(化名)和其女友劉穎冷蚂,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體汛闸,經...
    沈念sama閱讀 45,655評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡蝙茶,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,846評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了蛉拙。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,965評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡孕锄,死狀恐怖吮廉,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情畸肆,我是刑警寧澤宦芦,帶...
    沈念sama閱讀 35,684評論 5 347
  • 正文 年R本政府宣布,位于F島的核電站恬涧,受9級特大地震影響提揍,放射性物質發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,295評論 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望杉武。 院中可真熱鬧圾亏,春花似錦曹铃、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,894評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至柑肴,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間些侍,已是汗流浹背岗宣。 一陣腳步聲響...
    開封第一講書人閱讀 33,012評論 1 269
  • 我被黑心中介騙來泰國打工余指, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留淮韭,地道東北人捞慌。 一個月前我還...
    沈念sama閱讀 48,126評論 3 370
  • 正文 我出身青樓啸澡,卻偏偏與公主長得像,于是被迫代替她去往敵國和親氮帐。 傳聞我的和親對象是個殘疾皇子嗅虏,可洞房花燭夜當晚...
    茶點故事閱讀 44,914評論 2 355

推薦閱讀更多精彩內容