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.
'Archive until 15 Jul 2021 > Learning new stuffs' 카테고리의 다른 글
How to use <Prettier> code formatter on VS code, on save (0) | 2021.01.09 |
---|---|
Setting up routing through express (0) | 2021.01.03 |
Promise pattern (0) | 2021.01.02 |
Asynchronous (0) | 2021.01.02 |