hajinny 2021. 1. 2. 10:46

Prerequisite: read <Asynchronous> article, to understand how setTimeout works.

 

Using setTimeout, we can do very fun stuff.

setTimeout(()=>{console.log('hi');console.log('I can do lots of stuff');}, 1000)

()=>{//stuffs} is a function that will be scheduled to be executed (queued to the end of the code). This should be familiar from the last larticle.

 

function delay(sec, callb){
	setTimeout(()=>callb(new Date().toISOString()),1000*sec)
}

delay(5,(param)=>console.log(param))

This is working in a way that:

- when the last line is executed, function (param)=>console.log(param) is passed to delay as a parameter 'callb'

- setTimeout() passes ()=>callb(new Date().toISOString()) to timer thread, and makes timer count 5 seconds

- after 5 seconds, ()=>callb(new Date().toISOString()) is queued to be executed by javascript thread

- ()=>callb(new Date().toISOString()) is the same thing as:

()=>{

console.log(new Date().toISOString())

}

- so when ()=>callb(new Date().toISOString()) is executed, console.log(new Date().toISOString()) is executed, printing the date time of that instant.

 

So this is basically how callback function (function to be called later) is implemented in javascript.