Lesson 2 · Unit 03
Staying responsive
Long tasks, yielding, debounce, throttle and workers
What you practise
- Long tasks and input delay, yielding, debounce and throttle built and run, moving work to a worker
Try a question from this lesson
Pick one
A click handler needs 400 ms to filter a list. The user taps another button 100 ms after it starts. When can the second tap's handler begin?
Correct answer
In 300 ms, when the first handler has finished
Why
The main thread runs one task at a time and cannot interrupt it. The second tap is queued, not lost, and waits out the remaining 300 ms. To the user that is a button that did nothing for a third of a second.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Yielding
A long task cannot be interrupted, but it can be written as several short ones. Do a chunk, hand the thread back, continue in a new task.
Input that arrived meanwhile runs in the gap. The total work is the same or slightly more; what changes is the longest wait.
setTimeout(next, 0) queues the rest as a new task. Where it is supported, scheduler.yield() does the same and resumes sooner.
one task [========= 200 ms =========]
tap waits ---------->
chunks [50] [50] [50] [50]
tap runs here ^Concept
Debounce and throttle
Typing, scrolling and resizing fire events far faster than you need to react.
Debounce waits until the events have stopped for a set time, then runs once. Use it when only the final state matters: search after the user stops typing.
Throttle runs at once, then at most once per interval while the events continue. Use it when you need steady updates: a progress bar during a scroll.
Here the wait is 3 ticks, x is an event and R is a run.
time 0 1 2 3 4 5 6 7 8 9 10 11
events x x x x . . . x x . . .
debounce . . . . . . R . . . . R
throttle R . . R . . . R . . . .Concept
A clock you control
Code about time should never be tested by really waiting: it is slow, and a busy machine changes the result.
Use a fake clock. setT(fn, ms) records when fn is due and returns an id. at(ms) moves time forward one millisecond at a time and runs whatever has come due. A matching clearT(id) cancels a timer by emptying its slot.
Ten seconds of timers run in an instant and give the same answer every time.
let now = 0;
const timers = [];
function setT(fn, ms) {
timers.push({ due: now + ms, fn });
return timers.length - 1;
}
function at(ms) {
while (now < ms) {
now++;
timers.forEach((t, i) => {
if (!t || t.due > now) return;
timers[i] = null;
t.fn();
});
}
}9 more exercises in the app
- 4× type the answer
- 2× multiple choice
- 2× fill the blanks
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.