Synchronous & Asynchronous

Behavior

sync codepen demo

doc write, bar width examples

Rendering   Loop

  • Player 1 any changes?
  • Player 2 any changes?
  • Process Input
  • Calculate Game State
  • Render to screen

Rendering   Loop

https://developers.google.com/web/fundamentals/performance/rendering/

for(let i = 0; i < 100; i += 1){
    bar.style.width = i + "%";
}

recalculates styles of each element

recalculates how elements affect each other

Each layer is drawn graphically in memory

All layers combined

(opacity, order)

Synchronous Code

  • line-by-line execution
  • function calls
  • Loops (of all varieties)
//line-by-line execution
let const a = 5;
a += 1;


//function calls
const double a => a*2
    , four = double(2)
    , five = 5;


//loops
for(let i = 0; i < 10; i += 1){
    log(i);
}
log(i)

Asynchronous

Behavior

In general, asynchronous (from Greek asyn-, meaning "not with," and chronos, meaning "time") is an adjective describing objects or events that are not coordinated in time.

Asynchronous Actions

  • User Input
    • mouse, keyboard
  • Network Responses
    • API, Services
  • Web Workers
    • multi-threaded computations, functions
  • Timers
    • setInterval, setTimeout

Rendering   Loop

Async

Code

Result

...

...

Fetch

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Function which provides a easy and flexible API for accessing network resources

(is asynchronous)

fetch(something)
    .then(a function which handles data)
    .catch(a function which handles errors)

Fetch

fetch("http://www.domain.com/api/v1/people/30")

    .then(response => {
        console.log("I got the data!");
        const prettyData = response.map(...).filter(...)

        render(prettyData);
    })

    .then(...) //chainable

    .catch(response => {
        console.log("there was a network error!");
        render(errorMessage);
    });

Reddit API Example

Assignment

https://weber.instructure.com/courses/422412/assignments/3159375

Made with Slides.com