CodePeek · Free JavaScript classroom activity · 1 / 3
Promise vs setTimeout
LEARNER HANDOUT · Predict before running
Read the snippet independently. Write what each log prints, one output per line, without string quotes. Explain what runs now and what waits.
Treat each snippet as an independent, isolated browser script. Every Promise.resolve() here is already fulfilled and each snippet has one timer. Predict output order, not elapsed time: a requested 0 ms delay is not an exact execution time. This activity does not model unrelated browser work or every event-loop phase.
1. A Promise and a zero-delay timer
console.log("start");
setTimeout(() => {
console.log("timer");
}, 0);
Promise.resolve().then(() => {
console.log("promise");
});
console.log("end");My predicted output:
My reasoning: what runs synchronously, what is queued, and when do the callbacks run?
CodePeek · Free JavaScript classroom activity · 2 / 3
Promise vs setTimeout
LEARNER HANDOUT · Predict before running
Read the snippet independently. Write what each log prints, one output per line, without string quotes. Explain what runs now and what waits.
Treat each snippet as an independent, isolated browser script. Every Promise.resolve() here is already fulfilled and each snippet has one timer. Predict output order, not elapsed time: a requested 0 ms delay is not an exact execution time. This activity does not model unrelated browser work or every event-loop phase.
2. A microtask queues another microtask
setTimeout(() => {
console.log("timer");
}, 0);
Promise.resolve().then(() => {
console.log("first");
Promise.resolve().then(() => {
console.log("nested");
});
});
Promise.resolve().then(() => {
console.log("second");
});
console.log("sync");My predicted output:
My reasoning: what runs synchronously, what is queued, and when do the callbacks run?
CodePeek · Free JavaScript classroom activity · 3 / 3
Promise vs setTimeout
LEARNER HANDOUT · Predict before running
Read the snippet independently. Write what each log prints, one output per line, without string quotes. Explain what runs now and what waits.
Treat each snippet as an independent, isolated browser script. Every Promise.resolve() here is already fulfilled and each snippet has one timer. Predict output order, not elapsed time: a requested 0 ms delay is not an exact execution time. This activity does not model unrelated browser work or every event-loop phase.
3. A Promise created inside a timer
setTimeout(() => {
console.log("timer");
Promise.resolve().then(() => {
console.log("inside");
});
console.log("timer end");
}, 0);
Promise.resolve().then(() => {
console.log("promise");
});
console.log("sync");My predicted output:
My reasoning: what runs synchronously, what is queued, and when do the callbacks run?