+++ title = '⏳ Asynchrony : outside time' headless = true time = 30 facilitation = false emoji= '🧩' [objectives] 1="Define asynchrony" 2="Explain why we need asynchrony" 3="Identify an asynchronous method we have already used" +++
We can handle latency using {{}}run code in a different order.{{}} To understand asynchrony we first need to be clear about {{}}run code in the order it is written.{{}}.
We have written a lot of JavaScript programs that execute sequentially. This means that each line of code is run in order, one after the other. {{}}
console.log("first");
console.log("second");
console.log("third");
<--->
first
second
third
{{}} Each line of code is run in order. This is synchronous execution. We do this because JavaScript is {{}} A single thread can do one thing at a time. JavaScript is a single threaded language. {{}}.
When we call a function, the function will run to completion before the next line of code is executed. But what if we need to wait for something to happen? What if we need to wait for our data to arrive before we can show it? In this case, we can use asynchronous execution.
{{}} {{}} We have already used asynchronous execution. We have defined eventListeners that listen for events to happen, then execute a callback function. But here's a new idea: eventListeners are part of the Event API. They are not part of JavaScript! 🤯
When you set an eventListener you are really sending a call to a Web API and asking it do something for you.
const search = document.getElementById("search");
const waitForEvent = search.addEventListener("input", handleInput);
The callback handleInput
cannot run until the user types. With fetch
, the callback function cannot run until the data arrives. In both cases, we are waiting for something to happen before we can run our code.
{{}}
{{}}
graph LR
TimeProblem[🗓️ Time Problem] --> |caused by| SingleThread[🧵 Single thread]
SingleThread --> |send tasks to| ClientAPIs
TimeProblem --> |solved by| Asynchrony[🛎️ Asynchrony]
Asynchrony --> | delivered with | ClientAPIs{💻 Client APIs}
ClientAPIs --> |like| setTimeout[(⏲️ setTimeout)]
ClientAPIs --> |like| eventListener[(🦻🏾 eventListener)]
ClientAPIs --> |like| fetch[(🐕 fetch)]