今日已更新 339 条资讯 | 累计 19899 条内容
关于我们

RxJS in Angular — Chapter 9 | Timing Operators — debounceTime, throttleTime, interval & More

Jack Pritom Soren 2026年07月10日 14:38 1 次阅读 来源:Dev.to

👋 Welcome to Chapter 9! Imagine a user typing in a search box. They type "i", "ip", "iph", "ipho", "iphon", "iphone" — 6 keystrokes in 2 seconds. Do you really want to make 6 API calls ? Of course not! You want to wait until they stop typing and then search once. That's what timing operators solve. They control when and how often values flow through your stream. ⏱️ debounceTime() — Wait for the Silence debounceTime(ms) waits until there's a pause of ms milliseconds, THEN lets the latest value through. Think of it like this: "Ignore everything until they stop for a moment." Like a person who waits for you to finish talking before responding. import { debounceTime } from ' rxjs/operators ' ; // User types fast: 'i' → 'ip' → 'iph' → 'ipho' → 'iphon' → 'iphone' // debounceTime(400) waits 400ms of silence, then sends 'iphone' only searchControl . valueChanges . pipe ( debounceTime ( 400 )) . subscribe ( term => { this . searchProducts ( term ); // Only called ONCE with 'iphone'! }); Timeline: Type 'i' → [400ms timer starts] Type 'ip' → [reset timer] Type 'iph' → [reset timer] Type 'iphone'→ [reset timer] ... 400ms silence ... EMIT: 'iphone' ✅ Real Angular Example — Smart Search Box import { Component , OnInit , OnDestroy } from ' @angular/core ' ; import { FormControl } from ' @angular/forms ' ; import { Observable , Subject } from ' rxjs ' ; import { debounceTime , distinctUntilChanged , switchMap , startWith , takeUntil } from ' rxjs/operators ' ; @ Component ({ selector : ' app-search-box ' , template : ` <div class="search-wrapper"> <input [formControl]="searchControl" placeholder="Search products..." (keyup.escape)="clearSearch()"> <span *ngIf="isLoading" class="spinner">🔄</span> <button *ngIf="searchControl.value" (click)="clearSearch()">✕</button> </div> <div class="results-count" *ngIf="(results$ | async) as results"> Found {{ results.length }} results </div> <div class="results"> <div *ngFor="let item of results$ | async" class="result-item"> <strong>{{ item.nam

本文内容来源于互联网,版权归原作者所有
查看原文