Event Loop in Javascript

I like to record what I learned from technical salon or some thoughts inspired by group discussion. Today's group discussion topic is async and performance in You don’t know JS. Actually, what impressed me a lot is the extension points we discussed about Event Loop in Javascript, below I'd like to record it.

First袭异,I would like to Introduce a conception

What is event loop捐祠?

// `eventLoop` is an array that acts as a queue (first-in, first-out)

var eventLoop = [ ];

var event;

// keep going "forever"

while (true) {

// perform a "tick"

? ?if (eventLoop.length > 0) {

? ? ? // get the next event in the queue

? ? ? event = eventLoop.shift();

? ? ? // now, execute the next event

? ?try {

? ? ? event();

? ?}

? ?catch (err) {

? ? ? reportError(err);

? ?}

}

}

The above code are easy to understand. Pop every unit in eventLoop out and try to execute.?

Below is the code need to discuss.

var res = [];

// `response(..)` receives array of results from the Ajax call

function response(data) {

// let's just do 1000 at a time

var chunk = data.splice( 0, 1000 );

// add onto existing `res` array

res = res.concat(

// make a new transformed array with all `chunk` values doubled

chunk.map( function(val){

return val * 2;

} )

);

// anything left to process?

if (data.length > 0) {

// async schedule next batch

setTimeout( function(){

response( data );

}, 0 );

}

}

// ajax(..) is some arbitrary Ajax function given by a library

ajax( "http://some.url.1", response );

ajax( "http://some.url.2", response );

Albert said:“Does these codes will accelerate the speed?If not, why we write code like this静浴?”

The answer in my mind is to make program smoothly.But Lucky provide a more professional answer.

We simulated a parallel status which only read 1000 items data when data are too huge and page turn to blocking.

The key point is what is the core of this fake parallel?

setTimeout(fn, 0);

These codes seems simple, execute fn after 0 second.Albert present a core code as below:

function a(){

? ?...

? ?b();

? ?...

}

function b(){

? ?...

? ?setTimeout(d, 0);

? ?c();

? ?...

}

function c(){

...

}

function d(){

? ?...

}

How does Event Loop work糙置?

What is the running sequence of these codes?

Please continue to read if your answer is a, b, d, c.

Obviously, this answer is incorrect, the correct answer is: a, b, c, d

So what is the running principle of setTimeout(d,0)?? And why single thread javascript can have same function with setTimeout?

Now we can lead in eventLoop which was mentioned in the beginning.

Single thread means that all tasks need to queue, one by one.? ? At 21st century, CPU is more power than before. They can solve plenty of tasks during most of time. IO devices, by contrast, are so slow that CPU need to be idle to wait for them(.e.g ajax actions).

Designer of Javascript has already realized it撩匕,main thread can completely regardless of the IO equipment, hang in this task and run next one.Wait until the IO device returns the results, and then turn around, to carry out the pending mission.

So, all tasks can be divided into two types, one is the synchronous task, the other is the asynchronous task.Synchronous task refers to the task of queuing in the main thread.Asynchronous task refers to, do not enter the main thread, and into the "task queue" (task queue) task, only the "task queue" notify the main thread, an asynchronous task can be implemented, the task will enter the main thread of execution.

Synchronous task will be run only when previous on is finished.

———translated from the blog of Mr. Ruan Yifeng《Explain the operation mechanism of Javascript: Event Loop》

Back to see the above section of code. Fn a() is running and be added into stack until fn b appear.At this time, something associated with a() like context, pointer and so on will be pushed into heap.The same thing occurred on b() and c().The only question is when will the method in b()?setTimeout?be called?

setTimeout?will cause d() be pushed into eventLoop when it is running.

When the entire stack and heap is empty, that is, the main thread is idle, it will start to view the eventLoop, compared to each of the event time stamp蜓堕,

If the timestamp expires, call the event. If event does not meet the conditions of the start of the next process.

Above is my own understanding and some thinking for the contents of Albert told today.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末蜂嗽,一起剝皮案震驚了整個(gè)濱河市苗膝,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌植旧,老刑警劉巖辱揭,帶你破解...
    沈念sama閱讀 222,590評論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件离唐,死亡現(xiàn)場離奇詭異,居然都是意外死亡问窃,警方通過查閱死者的電腦和手機(jī)亥鬓,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,157評論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來域庇,“玉大人嵌戈,你說我怎么就攤上這事√螅” “怎么了熟呛?”我有些...
    開封第一講書人閱讀 169,301評論 0 362
  • 文/不壞的土叔 我叫張陵,是天一觀的道長尉姨。 經(jīng)常有香客問我庵朝,道長,這世上最難降的妖魔是什么又厉? 我笑而不...
    開封第一講書人閱讀 60,078評論 1 300
  • 正文 為了忘掉前任九府,我火速辦了婚禮,結(jié)果婚禮上覆致,老公的妹妹穿的比我還像新娘侄旬。我一直安慰自己,他們只是感情好篷朵,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,082評論 6 398
  • 文/花漫 我一把揭開白布勾怒。 她就那樣靜靜地躺著,像睡著了一般声旺。 火紅的嫁衣襯著肌膚如雪笔链。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,682評論 1 312
  • 那天腮猖,我揣著相機(jī)與錄音鉴扫,去河邊找鬼。 笑死澈缺,一個(gè)胖子當(dāng)著我的面吹牛坪创,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播姐赡,決...
    沈念sama閱讀 41,155評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼莱预,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了项滑?” 一聲冷哼從身側(cè)響起依沮,我...
    開封第一講書人閱讀 40,098評論 0 277
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后危喉,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體宋渔,經(jīng)...
    沈念sama閱讀 46,638評論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,701評論 3 342
  • 正文 我和宋清朗相戀三年辜限,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了皇拣。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,852評論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡薄嫡,死狀恐怖氧急,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情岂座,我是刑警寧澤态蒂,帶...
    沈念sama閱讀 36,520評論 5 351
  • 正文 年R本政府宣布,位于F島的核電站费什,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏手素。R本人自食惡果不足惜鸳址,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,181評論 3 335
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望泉懦。 院中可真熱鬧稿黍,春花似錦、人聲如沸崩哩。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,674評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽邓嘹。三九已至酣栈,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間汹押,已是汗流浹背矿筝。 一陣腳步聲響...
    開封第一講書人閱讀 33,788評論 1 274
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留棚贾,地道東北人窖维。 一個(gè)月前我還...
    沈念sama閱讀 49,279評論 3 379
  • 正文 我出身青樓,卻偏偏與公主長得像妙痹,于是被迫代替她去往敵國和親铸史。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,851評論 2 361

推薦閱讀更多精彩內(nèi)容

  • 爸在外面怯伊,沒趕回來過元宵節(jié)琳轿,今天給我爸打電話說不換票了 ,還是明天下午走,我分明聽到他在電話那邊強(qiáng)忍著語氣給我說話...
    Hoo志強(qiáng)閱讀 120評論 0 0
  • 代 理 詞 尊敬的審判長利赋、審判員 遼寧海星律師事務(wù)所根據(jù)相關(guān)法律規(guī)定接受本案原告的委托水评,指派我擔(dān)任原告與被告人身損...
    口無遮攔的人閱讀 1,205評論 0 0
  • 對于慢熱型的人,常常在細(xì)微中慢慢接受一個(gè)人媚送、一件事中燥、一段感情,他們常常顯得比較穩(wěn)重塘偎,其實(shí)心里特別有想法疗涉,他們甚至有...
    丁小喵治愈說閱讀 561評論 0 0
  • 有你的世界 更加輕緩溫和 有你的家 更加親密和諧
    凱瑟琳楊閱讀 82評論 0 0