JavaScript course · Part 5: Waiting · lab 6 of 11
Waiting: timers, promises and fetch
Why JavaScript cannot simply wait, what a promise is, async and await, and the shape of a real request including the error handling everybody skips.
By the end you can
- Delay work, and cancel it when it is no longer wanted
- Say what a promise is and what its three states mean
- Write async code that reads top to bottom, with errors handled
- Write a request properly: loading state, failure state, and the check everyone forgets
Easier if you did first
step 1 of 4
Doing something later
JavaScript does one thing at a time. There is a single queue of work, and while your code is running, nothing else can happen: no clicks, no scrolling, no drawing.
That is why there is no sleep function. If JavaScript could pause, the whole page would freeze for that long.
Instead you hand work to the browser to do later. setTimeout(fn, 1000) means run this function in about a second, once the current work is finished. setInterval repeats it.
'About' is the honest word. The delay is a minimum, not a promise: if something slow is running when the time comes, your function waits its turn.
Both return an id, and both need cancelling when the thing they were for is gone: clearTimeout and clearInterval. An interval on a panel that has closed keeps running forever, and that is a real memory leak you will meet in other people's code.
One pattern worth having: debouncing. On every keystroke in a search box you cancel the previous timer and set a new one, so the work only happens once the person stops typing. Without it, a search box can fire thirty requests while someone types one word.
Build the debounced search on the right.
const id = setTimeout(() => console.log("later"), 1000);
clearTimeout(id);
let timer;
function onType(text) {
clearTimeout(timer);
timer = setTimeout(() => search(text), 300);
}What these words mean
- setTimeout
- Run this once, after at least this many milliseconds.
- setInterval
- Run this again and again, with that gap.
- clearTimeout / clearInterval
- Cancel a timer using the id it returned.
- single threaded
- JavaScript does one thing at a time, so slow code freezes the page.
- debounce
- Wait until things go quiet before acting. Used for search-as-you-type.
Easy to get wrong
setInterval with no clearInterval
Always keep the id and clear it
The interval keeps running after the thing it belongs to is gone, doing work nobody sees, and it holds on to everything it references. On a long-lived page that is a leak.
A long loop to 'wait' for something
setTimeout, or a promise
A busy loop blocks the single thread, so the page stops responding completely. Nothing can be clicked and nothing is drawn until it ends.
What we check
- The previous timer is cancelled
- The wait is 300ms
- Only one search ran
- And it searched for the whole word
Nothing printed yet. Run your code.