grayshine
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # <font class="h2">執行緒與同步、非同步</font> ###### tags: `javascript` <style> .h2 { background: linear-gradient(135deg,#fff,#537479) ; color: #537479; display:block; padding: 6px 5px; border-radius: 4px; } .h3 { background: linear-gradient(180deg,#fff 50%,#c9d5d4) ; color: #537479; display:block; padding: 6px 5px; border-bottom: 3px solid #537479; } .h4 { color: #537479; font-weight:bold; font-size:1.1em; } </style> <br> :::info 非同步:程式中包含「子程式」時產生 Ajax、settimeout時會發生 ::: <br> javaScript 是一個==單線程/單執行緒==(single threaded)語言,在於JavaScript只能==一次執行一個statement(陳述式)==。 而「同步」指的是==同一時間只做一件事== 非同步指的則是==程式所執行的先後順序的差異==。 在非同步的處裡方式下,主程式的運行還是會繼續,而非同步進行的工作也還是會進行,只是不是馬上。而是等到主程式執行完畢,javaScript引擎有空檔後才會被執行。 <br> ### <font class="h3">解決非同步的方法</font> 1. 回呼函示(早期) 2. Promise物件(es6) 3. Async/Await(es6) <br> ### <font class="h3">Event Queue與 Event Loop</font> Event Queue、Event Loop這兩個部分並不存在於JavaScript內,而是瀏覽器的其中一部份。 然而瀏覽器內可不只有 JS 引擎,接下來我們要提到一個很重要的概念 — 「 Queue 」(又稱 Message / Event / Callback Queue )。 整個瀏覽器的運行環境並非只由 JS 引擎組成。因為 JS 語言特性屬於單執行緒,同時又為了讓網頁具有像「監聽事件」、「計時」、「 拉第三方API 」這些類似「背景作業」的功能,瀏覽器提供了另外一些部分來達成,分別是: 1. Event Queue 2. Web API 3. Event Table 4. Event Loop ### <font class="h4">Event Queue</font> :::info Event Queue像一個待辦事項清單,在裡面的程式邏輯並不會馬上被執行,而會等待整個javaScript的執行環境,也就是直到所有函式執行環境與全域執行環境全部結束,才開始逐一檢查並執行這個空間裡面有沒有等待執行的內容。 ::: Queue (儲列)是什麼樣的概念呢? 我們先來看一下,在寫網頁程式的時候,有一些所謂「內建的」API 如 `SetTimeout` / `setInterval `,這些 API 不存在於 JavaScript 原始碼內,但你仍然可以在開發時直接使用。因為這些 API 是屬於瀏覽器提供的 Web API 。Web API 並非 JS 引擎的一部分,但他屬於瀏覽器運行流程的一環。 setTimeout是一個全域函數,用於將想做的事情延後幾秒進行。 setInterval是根據給定的時間,固定幾秒進行 關於 Web API ,舉一些例子: - 操作 DOM 節點的 API 如 :document.getElementById - AJAX 相關 API 像是:XMLHttpRequest - 計時類型的 API ,就像剛剛提到的 setTimeout 這類 Web API 在與 JS 原始碼一起執行的時候,並不會直接影響 JS 主執行環境的運行,否則的話網頁在執行像是拉取第三方 API 資料的動作時,就只能乾等,無法執行任何其他事情了! 所以==瀏覽器將這些必須等待執行結果的動作,丟給其他部分去執行,然後讓 JS 引擎可以繼續做他應該做的事情,上述提到要等待執行結果的行為,其實也就是「非同步」的行為==。(因為不會一次直接從頭跑到尾做完) 這就是 Event Queue ( 事件儲列 )的工作了, 事件儲列專門用來存放這些非同步的函式,然後等到整個主執行環境運行結束以後,才開始依序執行事件儲列裡面的函式。而所謂 ==Queue 是一種「先進先出」的資料結構,與 Stack 的「後進先出」相反,所以先被推送到 Queue 裡面的函式會相對於其他函式優先被執行。== <br> ### <font class="h4">Event Loop</font> 那麼,什麼又是 Event Loop 呢?可以把 Event Loop 想成是另外一個幾乎無時無刻、每一毫秒都在執行的程式,他負責檢查現在主執行環境堆疊是否是空的?如果是空的,再去檢查 Event Queue ,若 Event Queue 有函式待執行,則將這些函式從 Event Queue 依序推出,並執行 <br> **範例:** ```javascript function eatBreakfast(){ console.log("吃早餐"); }; function washingPlate(){ console.log("洗餐盤"); }; function callSomeone(someone){ console.log("打給"+someone) setTimeout(function(){ console.log(someone+"回電"); },3000); } function doWork(){ var auntie = "漂亮阿姨"; eatBreakfast(); callSomeone(auntie); washingPlate(); } doWork(); ``` ![](https://i.imgur.com/pX8Pl21.png) ![](https://i.imgur.com/WmBNwme.jpg) <br> ![](https://i.imgur.com/JHztZjL.jpg) 1. JavaScript引擎執行到瀏覽器提供的`setTimeout`函式。 2. JavaScript引擎繼續運行,同時瀏覽器開始根據給定的秒數計時。 3. 等待計時完成後,把剛才接收到的函式推送到Event Queue內。 4. 等待JavaScript引擎運行完畢,主執行環境結束後,將Event Queue內的函式推送到JavaScript主執行環境,產生堆疊(執行該函式)。

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully