RxJS 14 ๐ฃ Schedulers & Concurrency โ Controlling execution timing with asyncScheduler, queueScheduler, asapScheduler, and animationFrameScheduler
Every RxJS value travels along two timelines that are easy to confuse: the moment the source produces it, and the moment the subscriber’s callback runs. For most operators the two are the same instant โ map transforms a value in the same tick it arrives, filter drops it without ever leaving the call stack. But a whole class of operators exists purely to move one of those moments onto a different queue, and the object that names the queue is a Scheduler. delay(1000) does not simply “wait”; it hands each notification to asyncScheduler, which parks it on the timer queue. When you write observeOn(asapScheduler) you are not adding a delay either โ you are moving delivery to the microtask queue, which drains after your current function returns but before the browser paints.
The distinction matters because JavaScript has at least five distinct places work can run: the call stack, the microtask queue, the render callbacks, the timer queue, and โ for RxJS specifically โ a synchronous trampoline that exists only inside the library. Each one has different ordering guarantees relative to the others and relative to a frame. Getting a DOM write onto the wrong one produces either a torn frame or a write that lands one frame late. Getting a test onto the wrong one produces a suite that takes ninety seconds and fails intermittently.
This chapter works through the whole surface. It starts with the SchedulerLike contract โ what a scheduler actually is, and why now() and schedule() are the entire interface. It then walks the four built-in schedulers one at a time, with the queue each one uses and the ordering you can rely on. From there it covers the two placement operators, observeOn and subscribeOn, which look similar and do entirely different things. It closes with the scheduler argument that nearly every time-based operator accepts, and the TestScheduler that turns a 300 ms debounce into virtual time that costs nothing.
Key point: A scheduler is not a delay. It is a reference to the queue where a piece of work runs, and RxJS exposes it through now() and schedule(). observeOn moves the delivery of notifications onto a queue; subscribeOn moves the subscribe() call itself. They do not overlap, and choosing the wrong one is the single most common scheduler bug.
Why schedulers exist
The task-queue problem. JavaScript is single-threaded but not single-queued. A promise callback runs in a microtask, which drains before rendering. A setTimeout callback runs in a macrotask, which runs after rendering. A requestAnimationFrame callback runs inside the frame, before paint. These are not interchangeable, and a raw Observable has no vocabulary for expressing which one its subscriber should run on. A scheduler is that vocabulary.
The stack-depth problem. Some operators are naturally recursive: expand resubscribes to its inner observable for every value, and a synchronous source makes that resubscription a new stack frame. Ten thousand synchronous values means ten thousand frames. A trampoline โ a queue that drains in a loop instead of recursing โ flattens the depth to one. queueScheduler is that trampoline, and it is the only reason a long synchronous chain does not overflow.
The frame-budget problem. A browser frame at 60 Hz gives you roughly 16.7 ms, and layout and paint consume most of it. A DOM write on the macrotask queue can arrive after the frame has already painted, producing a visible one-frame lag in an animation. A DOM write inside the frame callback โ animationFrameScheduler โ lands in the frame it was computed for. Nothing except a scheduler can express that constraint.
The determinism problem. A test that exercises debounceTime(300) with the real asyncScheduler takes 300 ms of wall clock and is subject to whatever else is on the event loop. The fix is not a fake timer library bolted on from outside; it is to make “now” and “schedule” injectable, which is exactly what SchedulerLike does. TestScheduler implements the same two methods against virtual time, so the source code under test does not change at all.
The trade-off. Every scheduler hop is a task boundary, and a task boundary is a break in ordering. Two observables interleaved synchronously arrive in a fixed order; move one of them onto asyncScheduler and the order becomes dependent on queue draining. Schedulers buy you control over when at the cost of control over exactly which turn. Use them where the queue genuinely matters and leave the rest alone.
a. The SchedulerLike contract
A scheduler is a very small object. The interface RxJS programs against has exactly two methods, and every built-in scheduler and the test scheduler implement both.
// The complete contract. Anything satisfying this is a valid scheduler,
// including a hand-written one for a queue the library does not know about.
interface SchedulerLike {
// The scheduler's clock in milliseconds. Time-based operators call this
// instead of Date.now(), which is what makes virtual time possible.
now(): number;
// Queue one unit of work. Returns a Subscription whose unsubscribe()
// cancels the work if it has not run yet.
schedule<T>(
work: (this: SchedulerAction<T>, state?: T) => void,
delay?: number,
state?: T
): Subscription;
}
The Scheduler class implements this and adds a flush() for the trampoline variants, but you almost never touch it directly. You consume schedulers by passing them as arguments, and you produce them only when writing a custom integration.
import { scheduled, asyncScheduler, animationFrameScheduler } from "rxjs";
// `scheduled` pairs any iterable with a scheduler, so every notification
// travels through that scheduler's queue rather than the call stack.
scheduled([1, 2, 3], asyncScheduler).subscribe((n) => console.log(n));
// `now()` is the clock. asyncScheduler returns Date.now(); the frame
// scheduler returns the frame timestamp; the test scheduler returns
// virtual frames. Code that reads Date.now() directly opts out of all three.
console.log(asyncScheduler.now()); // e.g. 1717171717171
console.log(animationFrameScheduler.now()); // e.g. 1043.2 (frame time)
Cancellation lives on the returned Subscription, and it is the same mechanism as everywhere else in RxJS. Unsubscribing a scheduled action that has not yet run removes it from the queue; unsubscribing one that has already run is a no-op.
import { asyncScheduler } from "rxjs";
// One deferred action on the timer queue, addressable for one second.
const task = asyncScheduler.schedule(() => console.log("ran"), 1000);
// Cancels the pending timer. Nothing runs, and the timer table entry is
// cleared โ no leak, no late callback.
task.unsubscribe();
b. The four schedulers
Each built-in scheduler is a reference to a different queue, and each has a distinct set of guarantees. They are not ordered by “speed” โ they are ordered by when in the task lifecycle the work runs.
queueScheduler โ the synchronous trampoline
queueScheduler runs work immediately, inside the call that scheduled it, unless another action is already running. In that case the new action is appended to a queue and drained by the active loop. That single rule is what makes it a trampoline: nested scheduling becomes iteration instead of recursion.
import { queueScheduler } from "rxjs";
queueScheduler.schedule(() => {
console.log("A: start");
// Scheduled while a flush is active, so this is appended to the queue
// rather than nested as another stack frame.
queueScheduler.schedule(() => console.log("B: queued"));
console.log("A: end");
});
// The flush drains before schedule() returns, so B runs before this line.
console.log("C: caller resumes");
// A: start โ A: end โ B: queued โ C: caller resumes
Because the first action runs inline, queueScheduler is the one scheduler that does not defer anything visible. It is chosen for stack-depth control and for flattening a recursive chain, never for “run this later”. Its clock is Date.now(), and a positive delay is not what it is for โ deferred work belongs on asyncScheduler.
import { range, of, expand, take, observeOn, queueScheduler } from "rxjs";
// Synchronous emission with no scheduler: `range` is a loop internally,
// so it is fine, but each value is delivered inside the subscribe() call.
range(0, 3).pipe(observeOn(queueScheduler)).subscribe((n) => console.log(n));
// The trampoline becomes load-bearing when the source is recursive.
// `expand` resubscribes for every value; the queue flattens the nesting
// so the stack depth stays at one regardless of how many values arrive.
of(0)
.pipe(
expand((n) => of(n + 1, queueScheduler)), // inner emission queued
take(100_000),
observeOn(queueScheduler) // delivery also queued
)
.subscribe();
asapScheduler โ the microtask queue
asapScheduler schedules onto a microtask โ internally a resolved promise’s .then(). Microtasks drain at the end of the current task, before the browser does anything else, including rendering. That makes asapScheduler the correct queue for “after the current synchronous block, but before anything the user can see.”
import { of, observeOn, asapScheduler } from "rxjs";
of(1).pipe(observeOn(asapScheduler)).subscribe(() => console.log("microtask"));
console.log("sync");
setTimeout(() => console.log("macrotask"), 0);
// sync โ microtask โ macrotask
// The microtask drains before the timer queue is even looked at.
The useful property is coalescing. Five separate observeOn(asapScheduler) deliveries triggered from one synchronous block all drain in the same microtask checkpoint, before the browser has a chance to paint anything. That is exactly the behaviour you want when a burst of state changes should produce one visible update.
asyncScheduler โ the timer queue
asyncScheduler is the default for almost every time-based operator, and it schedules onto the macrotask queue using setInterval internally. Its callbacks run after the current task and after any pending microtasks and rendering, so an emission here is always at least one turn later than the code that caused it.
import { of, observeOn, asyncScheduler } from "rxjs";
of(1).pipe(observeOn(asyncScheduler)).subscribe(() => console.log("macrotask"));
// Runs after everything synchronous and every pending microtask has drained.
console.log("sync first");
asyncScheduler.now() is Date.now(). This is the scheduler that delay, debounceTime, throttleTime, auditTime, sampleTime, timeout, bufferTime, windowTime, interval, and timer use when you do not pass one.
animationFrameScheduler โ the render callback
animationFrameScheduler schedules onto requestAnimationFrame, so the callback runs inside the browser’s frame, immediately before layout and paint. This is the only queue where a style write is guaranteed to be painted in the same frame it was computed for. In an environment without requestAnimationFrame it falls back to a ~16.7 ms setTimeout.
import { of, observeOn, animationFrameScheduler } from "rxjs";
of(0).pipe(observeOn(animationFrameScheduler)).subscribe(() => {
// Runs inside the frame callback, before paint. A transform written
// here is composited in this frame, not the next one.
element.style.transform = "translateX(120px)";
});
Scheduling directly against the scheduler, rather than through an operator, gives the canonical animation loop: an action that reschedules itself with the same start time so it can compute elapsed time from the frame clock.
import { animationFrameScheduler } from "rxjs";
// One action that reschedules itself each frame. `startTime` is carried
// through as the action's state so elapsed time is measured from frame 0.
animationFrameScheduler.schedule(
function (startTime: number) {
const elapsed = animationFrameScheduler.now() - startTime;
element.style.transform = `translateX(${Math.min(elapsed / 5, 320)}px)`;
// Rescheduling from inside the action appends exactly one frame.
if (elapsed < 2000) {
this.schedule(startTime, 0);
}
},
0, // delay
animationFrameScheduler.now() // initial state
);
c. observeOn โ moving delivery onto a scheduler
observeOn changes where the subscriber’s callbacks run. Every notification โ next, error, and complete โ is wrapped in a scheduled action, so the subscriber sees them on the scheduler’s queue instead of the source’s. The source itself keeps running wherever it ran before; only the delivery moves.
import { fromEvent, throttleTime, observeOn, animationFrameScheduler } from "rxjs";
// The input events arrive on the DOM's own turn. throttleTime reduces the
// rate but still delivers on asyncScheduler. observeOn then moves the
// delivery of every remaining notification onto the frame callback.
fromEvent(input, "input")
.pipe(
throttleTime(100),
observeOn(animationFrameScheduler)
)
.subscribe((e) => render(e.target.value));
// One style write per frame, aligned with paint.
The cost is one task per notification. On a fast source that is a flood of queued actions, each of which must be drained before the next can start. The fix is to bound the rate before the hop rather than after it.
// โ One scheduled action per emission. A 1000 Hz source queues 1000
// tasks per second and the subscriber falls progressively further behind.
fast$.pipe(observeOn(asyncScheduler)).subscribe(handle);
// โ
Bound the rate first, then hop. The scheduler now sees at most
// one notification per 16 ms, which is the frame budget.
fast$.pipe(throttleTime(16), observeOn(asyncScheduler)).subscribe(handle);
observeOn accepts a second argument โ an additional delay applied to every notification before it enters the queue. That is occasionally useful for staggered work, but it is not a substitute for delay: delay shifts the whole stream by a fixed amount, whereas observeOn(scheduler, ms) shifts each notification individually.
// Each notification waits 200 ms AND is then delivered on the timer queue.
source$.pipe(observeOn(asyncScheduler, 200)).subscribe(handle);
// The whole stream shifted by 200 ms, with no queue change.
source$.pipe(delay(200)).subscribe(handle);
d. subscribeOn โ moving the subscription
subscribeOn is the other half of the pair, and it operates on a different event entirely: it schedules the call to subscribe() on the source. It does not move emissions. On a cold source this looks like a delay because a cold source starts producing when it is subscribed to, but the mechanism is different and the difference is observable.
import { of, subscribeOn, asyncScheduler } from "rxjs";
// Without subscribeOn, `of` emits during the subscribe() call itself, so
// the values arrive before the next line runs.
of(1).subscribe((v) => console.log("inline", v));
console.log("after inline subscribe");
// inline 1 โ after inline subscribe
// With subscribeOn, the subscribe call on the source is a scheduled
// action. Nothing has been subscribed to when the next line runs.
of(1).pipe(subscribeOn(asyncScheduler)).subscribe((v) => console.log("deferred", v));
console.log("after deferred subscribe");
// after deferred subscribe โ deferred 1
The consequence on a hot source is the one people trip over. A Subject produces values whether or not anybody is listening, so deferring the subscription does not defer the values โ it makes you miss them.
import { Subject, subscribeOn, asyncScheduler } from "rxjs";
const subject = new Subject<number>();
// The subscription itself is scheduled. Until that action runs, the
// Subject has no observer.
subject.pipe(subscribeOn(asyncScheduler)).subscribe((v) => console.log(v));
subject.next(1); // missed โ the subscription has not been established
subject.next(2); // missed
// Later, when the microtask/task drains, the observer attaches. Only
// values emitted after that point are received.
Because the scheduled subscription is itself a Subscription, unsubscribing before the action runs cancels it cleanly โ the source is never subscribed at all.
// The scheduled subscribe is added to the returned Subscription, so a
// synchronous unsubscribe prevents the source from ever being touched.
const sub = expensive$.pipe(subscribeOn(asyncScheduler)).subscribe(handle);
sub.unsubscribe();
// expensive$ never subscribed: no socket, no request, no leak.
The two operators are frequently confused, so the rule is worth stating plainly. subscribeOn affects the start; observeOn affects each value. If you want the whole chain to begin on a different queue, use subscribeOn. If you want the subscriber to receive values on a different queue, use observeOn. If you want both, use both โ subscribeOn first in the pipe, observeOn last.
// Starts the chain on the timer queue, delivers every emission on the
// trampoline. Both hops are explicit and independent.
source$.pipe(
subscribeOn(asyncScheduler),
map(transform),
observeOn(queueScheduler)
).subscribe(handle);
e. Time-based operators and the testing scheduler
Nearly every operator that takes a duration also takes a scheduler as its final argument, defaulting to asyncScheduler. That last argument is the entire testing story: supplying a different scheduler swaps out the clock without touching the operator.
import { debounceTime, throttleTime, auditTime } from "rxjs";
// The scheduler is the second argument of each of these. Omitting it
// means asyncScheduler, and a real timer.
input$.pipe(debounceTime(300, testScheduler)).subscribe(search);
input$.pipe(throttleTime(300, testScheduler)).subscribe(search);
input$.pipe(auditTime(300, testScheduler)).subscribe(search);
// Operators that construct timers accept one too.
interval(1000, testScheduler).subscribe(tick);
timer(500, 1000, testScheduler).subscribe(tick);
TestScheduler implements SchedulerLike against virtual time. When you run inside testScheduler.run(...), RxJS swaps the default schedulers โ asyncScheduler, asapScheduler, and animationFrameScheduler โ for delegating versions that forward to the test scheduler. Every operator that did not receive an explicit scheduler now runs on virtual time anyway, so the code under test is exactly the production code.
import { TestScheduler } from "rxjs/testing";
import { debounceTime } from "rxjs";
const testScheduler = new TestScheduler((actual, expected) => {
expect(actual).toEqual(expected);
});
testScheduler.run(({ cold, expectObservable }) => {
// Inside `run`, one marble frame is 10 ms. debounceTime(30) is 3 frames.
const source = cold("-a----b------|");
// 0123456789...
// a and b are each followed by a gap longer than 3 frames, so each
// survives the debounce and is emitted 3 frames after it arrives.
expectObservable(source.pipe(debounceTime(30)))
.toBe("----a----b---|");
});
The gain is not just speed. Virtual time is deterministic: the debounce fires at a defined position relative to the source’s emissions, so the assertion tests the operator’s semantics rather than the machine’s scheduling. testScheduler.now() returns virtual milliseconds, and time() inside run lets you name progressions when a marble string would be unreadable.
Complete Example Session
// ============================================
// PART 1: THE FOUR QUEUES SIDE BY SIDE
// ============================================
import { of, observeOn, queueScheduler, asapScheduler, asyncScheduler }
from "rxjs";
console.log("1: sync start");
// queueScheduler flushes inline โ this runs before the next statement.
of("q").pipe(observeOn(queueScheduler)).subscribe((v) => console.log("2:", v));
// asapScheduler schedules a microtask.
of("a").pipe(observeOn(asapScheduler)).subscribe((v) => console.log("3:", v));
// asyncScheduler schedules a macrotask.
of("s").pipe(observeOn(asyncScheduler)).subscribe((v) => console.log("4:", v));
console.log("5: sync end");
// 1 โ 2 โ 5 โ 3 โ 4
// Inline first, then the microtask, then the timer. The order is a
// property of the queues, not of the sources.
// ============================================
// PART 2: THE TRAMPOLINE
// ============================================
queueScheduler.schedule(() => {
console.log("outer: start");
// Appended to the active flush, not nested on the stack.
queueScheduler.schedule(() => console.log("inner: queued"));
console.log("outer: end");
});
// outer: start โ outer: end โ inner: queued
// ============================================
// PART 3: MICROTASK BEATS MACROTASK
// ============================================
of(0).pipe(observeOn(asapScheduler)).subscribe(() => console.log("micro"));
setTimeout(() => console.log("macro"), 0);
// micro drains at the end of this task; macro runs in the next one.
// ============================================
// PART 4: THE FRAME LOOP
// ============================================
import { animationFrameScheduler } from "rxjs";
const loopSub = animationFrameScheduler.schedule(
function (startTime: number) {
const elapsed = animationFrameScheduler.now() - startTime;
element.style.transform = `translateX(${Math.min(elapsed / 4, 300)}px)`;
if (elapsed < 1500) {
this.schedule(startTime, 0); // one more frame
}
},
0,
animationFrameScheduler.now()
);
// ============================================
// PART 5: observeOn MOVES DELIVERY
// ============================================
import { fromEvent, throttleTime } from "rxjs";
fromEvent(window, "scroll")
.pipe(
throttleTime(16), // bound the rate first
observeOn(animationFrameScheduler) // then align with paint
)
.subscribe(() => layout());
// ============================================
// PART 6: subscribeOn MOVES THE SUBSCRIPTION
// ============================================
import { subscribeOn } from "rxjs";
of("value")
.pipe(subscribeOn(asyncScheduler))
.subscribe((v) => console.log("deferred:", v));
console.log("subscribed synchronously, source not yet touched");
// Prints the "subscribed synchronously" line first.
// ============================================
// PART 7: subscribeOn ON A HOT SOURCE LOSES VALUES
// ============================================
import { Subject } from "rxjs";
const hot = new Subject<number>();
hot.pipe(subscribeOn(asyncScheduler)).subscribe((n) => console.log("got", n));
hot.next(1); // dropped: the observer is not attached yet
// ============================================
// PART 8: EXPLICIT SCHEDULER INJECTION
// ============================================
import { scheduled, range, from } from "rxjs";
// of / from / range / scheduled each take a scheduler argument.
scheduled([10, 20], queueScheduler).subscribe(console.log);
from([30, 40], queueScheduler).subscribe(console.log);
range(50, 2, queueScheduler).subscribe(console.log);
// ============================================
// PART 9: VIRTUAL TIME IN TESTS
// ============================================
import { TestScheduler } from "rxjs/testing";
import { debounceTime } from "rxjs";
const testScheduler = new TestScheduler((a, e) => expect(a).toEqual(e));
testScheduler.run(({ cold, expectObservable }) => {
expectObservable(cold("-a----b------|").pipe(debounceTime(30)))
.toBe("----a----b---|");
});
// ============================================
// PART 10: CANCELLING A SCHEDULED ACTION
// ============================================
const task = asyncScheduler.schedule(() => console.log("never"), 5000);
task.unsubscribe(); // clears the pending timer; nothing runs
The ten parts covered the four queues in one ordering demonstration, the trampoline’s append-not-nest behaviour, the microtask-before-macrotask guarantee, a self-rescheduling frame loop, the two placement operators with their respective failure modes, explicit scheduler injection on the factory functions, virtual time in a marble test, and cancellation of a scheduled action.
Quick Reference
The Four Schedulers
| Scheduler | Underlying queue | Runs |
|---|---|---|
queueScheduler | Synchronous trampoline | Inline, after the active action |
asapScheduler | Microtask (Promise.then) | After sync code, before paint |
asyncScheduler | Timer (setInterval) | Next macrotask |
animationFrameScheduler | requestAnimationFrame | Inside the frame, before paint |
observeOn vs subscribeOn
| Operator | Moves | On a hot source |
|---|---|---|
observeOn(s) | Delivery of next / error / complete | Values still arrive, later |
observeOn(s, d) | Delivery, each notification delayed by d | Same |
subscribeOn(s) | The subscribe() call on the source | Values before the task are missed |
subscribeOn(s, d) | The subscribe, delayed by d | Same |
Scheduler Defaults
| Operator | Default |
|---|---|
delay, debounceTime, throttleTime | asyncScheduler |
auditTime, sampleTime, timeout | asyncScheduler |
bufferTime, windowTime | asyncScheduler |
interval, timer | asyncScheduler |
scheduled, from, range | None โ synchronous unless given one |
The SchedulerLike Contract
| Member | Purpose |
|---|---|
now() | The scheduler’s clock, in milliseconds |
schedule(work, delay?, state?) | Queue one action; returns a Subscription |
Subscription.unsubscribe() | Cancels the action if it has not run |
Explicit Scheduler Injection
| Factory | Argument position |
|---|---|
of(a, b, scheduler) | Last |
from(iterable, scheduler) | Second |
range(start, count, scheduler) | Third |
scheduled(iterable, scheduler) | Second |
interval(ms, scheduler) | Second |
Best Practices
โ Do This:
// Align DOM writes with the frame
fromEvent(el, "scroll").pipe(observeOn(animationFrameScheduler)); // โ
// Coalesce a synchronous burst before it paints
state$.pipe(observeOn(asapScheduler)).subscribe(render); // โ
// Bound the emission rate before a scheduler hop
fast$.pipe(throttleTime(16), observeOn(asyncScheduler)); // โ
// Defer the subscription, not the emissions
cold$.pipe(subscribeOn(asyncScheduler)).subscribe(handle); // โ
// Let the test scheduler own the clock
input$.pipe(debounceTime(300, testScheduler)); // โ
// Inject the scheduler at the factory site
scheduled(items, asyncScheduler); // โ
โ Don’t Do This:
// Expect subscribeOn to move emissions
hot$.pipe(subscribeOn(asyncScheduler)).subscribe(log); // โ
// Flood the queue with one task per emission
fast$.pipe(observeOn(asyncScheduler)).subscribe(handle); // โ
// Use queueScheduler to defer anything
work$.pipe(observeOn(queueScheduler)).subscribe(later); // โ
// Write styles on the timer queue during animation
value$.pipe(delay(16)).subscribe(applyStyle); // โ
// Call Date.now() inside an operator that could be virtual
map(() => Date.now()); // โ
// Wait on real timers in a unit test
await wait(300); // instead of testScheduler.run // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Animation lags a frame | Styles written on asyncScheduler | observeOn(animationFrameScheduler) |
| Subscription never happens | Unsubscribed before the scheduled action ran | Await or observe the subscription |
| Values missing on a hot source | subscribeOn deferred the subscribe call | Remove it, or buffer upstream |
| Queue backs up under load | One task per emission on asyncScheduler | throttleTime before the hop |
| Ordering changed unexpectedly | A hop split a synchronous sequence | Keep synchronous or use queueScheduler |
| Test takes seconds | Real asyncScheduler used in assertions | Pass testScheduler or use run() |
| Stack overflow in deep chains | Recursive resubscription with no trampoline | queueScheduler on the inner emission |
No emissions after a delay | delay defaults to asyncScheduler in a fake-timer context | Pass the scheduler explicitly |
Real-World Examples
1. Frame-aligned drag
fromEvent(el, "pointermove").pipe(
throttleTime(16),
observeOn(animationFrameScheduler)
).subscribe(position);
2. Coalesced state render
merge(setA$, setB$, setC$).pipe(observeOn(asapScheduler)).subscribe(render);
3. Deferred heavy subscription
expensive$.pipe(subscribeOn(asyncScheduler)).subscribe(handle);
4. Rescheduling animation loop
animationFrameScheduler.schedule(function (t) { draw(t); this.schedule(t, 0); }, 0, now());
5. Virtual-time debounce test
testScheduler.run(({ cold, expectObservable }) =>
expectObservable(cold("a-b--|").pipe(debounceTime(20))));
6. Cancelling a pending action
const task = asyncScheduler.schedule(flush, 250);
task.unsubscribe();
7. Explicit scheduler on a factory
scheduled([1, 2, 3], queueScheduler).subscribe(render);
8. Trampoline for deep recursion
of(0).pipe(expand((n) => of(n + 1, queueScheduler)), take(50_000)).subscribe();
9. Reading the scheduler clock
const elapsed = animationFrameScheduler.now() - start;
10. Microtask batch of DOM reads
merges$.pipe(observeOn(asapScheduler)).subscribe(measure);
Visual
The Five Queues
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ THE ORDER THE QUEUES DRAIN โ
โ โ
โ 1. call stack synchronous code runs here โ
โ 2. trampoline queueScheduler runs inline here โ
โ 3. microtask asapScheduler drains here โ
โ 4. render animationFrameScheduler runs here โ
โ 5. macrotask asyncScheduler runs here โ
โ โ
โ Each stage drains fully before the next one begins. โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
observeOn vs subscribeOn
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ TWO DIFFERENT EVENTS, TWO DIFFERENT OPERATORS โ
โ โ
โ subscribeOn(asyncScheduler) โ
โ source โโโโโโโบ subscribe() โโโ deferred โ
โ emissions still happen where they always did โ
โ โ
โ observeOn(asyncScheduler) โ
โ source โโโโโโโบ subscribe() โโโ not deferred โ
โ each next/error/complete โโโบ deferred โ
โ โ
โ Use both when both need to move. โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Trampoline
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ queueScheduler: APPEND, DO NOT NEST โ
โ โ
โ schedule(A) โ
โ โโ A begins โ
โ โโ schedule(B) while A is active โ
โ โ โโ B appended to the queue โ
โ โโ A ends โ
โ โโ B runs โ
โ โ
โ Stack depth stays at one for any number of queued items โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Frame Budget
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ONE FRAME (about 16.7 ms at 60 Hz) โ
โ โ
โ โโ rAF callbacks โโโ animationFrameScheduler here โ
โ โโ style + layout โ
โ โโ paint โ
โ โโ commit โ
โ โ
โ A write on asyncScheduler arrives after this frame has โ
โ already painted, so it is composited one frame late. โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| What a scheduler is | A reference to a queue, plus a clock |
| Contract | now() and schedule(work, delay, state) |
queueScheduler | Synchronous trampoline; runs inline |
asapScheduler | Microtask; before paint |
asyncScheduler | Timer queue; the default for time operators |
animationFrameScheduler | Frame callback; before paint, per frame |
observeOn | Moves delivery of next / error / complete |
subscribeOn | Moves the subscribe() call itself |
| Cost of a hop | One task per notification |
| Testing | TestScheduler.run swaps the default schedulers |
| Injection point | Last argument of of, from, range, interval |
Key takeaways:
- A scheduler names a queue, not a duration.
asyncScheduleris the timer queue,asapScheduleris the microtask queue,animationFrameScheduleris the frame callback, andqueueScheduleris a synchronous trampoline. Delay is a separate concept implemented by operators on top of these queues. observeOnandsubscribeOnoperate on different events.observeOnmoves each notification’s delivery;subscribeOnmoves the onesubscribe()call. Confusing them produces orderings that look random and are entirely deterministic.subscribeOnon a hot source drops values. ASubjecthas no replay, so deferring the subscription means the observer attaches after emissions have already happened. It is safe only on cold sources.queueScheduleris for stack depth, not for deferral. It runs work inline, and its only real purpose is flattening recursive resubscription so the call stack stays bounded.- Every hop costs a task.
observeOn(asyncScheduler)on a high-frequency source queues one action per notification. Bound the rate withthrottleTimebefore the hop, not after. - The scheduler argument is the testing seam.
TestSchedulerimplements the same two methods against virtual time, andtestScheduler.runswaps the defaults so the production code runs unchanged at zero cost.
Remember: Schedulers exist because JavaScript has several queues with different ordering guarantees, and an Observable alone cannot say which one its subscriber should run on. Read observeOn as “deliver here” and subscribeOn as “start here”, reach for animationFrameScheduler whenever a DOM write must land in the frame it belongs to, and reach for queueScheduler only when recursion threatens the stack. Keep the hops few and deliberate โ each one buys control over timing and gives up a guarantee about ordering โ and always pass the scheduler through as the last argument so that the test can replace the clock without touching the code.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!