JS — Call back, Async

Youngmin Park
2 min readMar 21, 2021

JavaScript is synchronous. which mean It execute the code block by order after hoisting.

Hoisting: var, function declaration

look at example below

synchronous.

It printed ‘1’, ‘2’, ‘3’. synchronously.

but you can change some order here to be printed.

see the below

asynchronous, use setTimeout

now it printed ‘1’, ‘3’, ‘2’.

what is going on here is it print ‘1’ first then tell browser to print ‘2’ after 1000 millisecond(1 second) later but they don’t wait until ‘2’ is printed thus it printed ‘3’ then print ‘2’ at the end.

you can use arrow function to make more simple.

arrow function

Synchronous callback

question. do I need callback function only for asynchronous?

the answer is ‘NO’.

you can use callback for synchronous too. see the below

use callback function for Synchronous

‘1’, ‘3’, ‘hello’, ‘2’ printed.

what happened inside of JS engine?

hoisting is happened.

function is hoisted. so the logic was like below.

Asynchronous callback

everything is same but ‘async callback’ is printed at the end

see what’s going on in JS engine below

all function is hoisted

line 14, ‘1’ is printed (sync).

line 16 wait for 1 second(async)

line 17, ‘3’ is printed(sync)

line 19, ‘hello’ is printed(sync)

all synchronous are printed

then

line 16 ‘2’ is printed because 1 second is passed.(async)

line 21, ‘async callback is printed because 2 second is passed(async)

These are simple example of callback and async

Thank you

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Youngmin Park
Youngmin Park

No responses yet

Write a response