First we need to understand
if (stack.isEmpty) {
if (!queue.isEmpty) {
const item = queue.shift()
stack.push(item)
}
}
if you want to do something before browser paints - requestAnimationFrame
requestAnimationFrame(() => {
console.log('do after 1st animation')
})
if you want to do something after browser paints - nested use of requestAnimationFrame
requestAnimationFrame(() => {
requestAnimationFrame(() => {
console.log('do after 1st animation')
})
})
3 states
new Promise(() => {}) // Pending
new Promise((res, rej) => res('Yay')) // Fullfilled
new Promise((res, rej) => rej('oh no')) // Rejected
shorthand syntax
Promise.resolve('Yay!')
Promise.reject('oh no')
console.log('start')
setTimeout(() => {
console.log('timeout')
}, 0)
Promise.resolve('promise!').then((res) => console.log(res))
console.log('end')
// output:
// start
// end
// promise
// timeout
const one = () => Promise.resolve('promise')
async function myFunc() {
console.log('start of func')
const res = await one()
console.log(res)
console.log('end of func')
}
console.log('before function')
myFunc()
console.log('after function')
//output:
// before function
// start of func
// after function
// promise
// end of func
const one = () => Promise.resolve('one')
function myFunc() {
console.log('start of func')
one().then((res) => console.log(res))
console.log('end of func')
}
console.log('before function')
myFunc()
console.log('after function')
//output:
// before function
// start of func
// end of func
// after function
// promise
const callStack = []
const microTaskQueue = []
const animationQueue = []
const taskQueue = []
while (1) {
while (callStack.length != 0) {
const item = callStack.pop()
process(item) // can generate new element on stack; therefore can lead to stack overflow
}
while (microTaskQueue.length > 0) {
const item = microTaskQueue.shift()
process(item) // can generate new microtask; can create infinite loop
}
const temp = animationQueue
animationQueue = []
while (temp.length > 0) {
const item = temp.shift()
process(item) // new items will be added to animationQueue which is different than this
}
if (taskQueue.length != 0) {
const item = taskQueue.shift()
callStack.push(item)
}
}