大网数据广告活动
Web 标准与前端开发

Observable: take() method

· 52CE 我爱测

The **`take()`** method of the Observable interface returns a new observable that emits the given number of values from the start of the source observable and then completes.

Observable API

The take() method of the Observable interface returns a new observable that emits the given number of values from the start of the source observable and then completes.

Syntax

take(amount)

Parameters

  • amount
    • : The number of values to take from the start of the source observable. It should be an unsigned integer.

Return value

A new Observable. When subscribed to, it emits values from the source observable until amount values have been emitted or the source completes, whichever comes first. Once the limit is reached, it completes and unsubscribes from the source.

Description

Like other observable-returning operators, this method is lazy: calling it creates a new observable without subscribing to the source. Processing starts when the returned observable is subscribed to.

If amount is 0, the returned observable completes immediately when subscribed to, without subscribing to the source. Errors from the source are forwarded until the returned observable completes.

Examples

Using take()

This example counts the first five button clicks. On the fifth click, the count is replaced by a completion message, and subsequent clicks are ignored. Click Restart after the stream ends to try again.

<button>Click me</button>
<p>Click count: 0</p>
<button id="restart" disabled>Restart</button>
const btn = document.querySelector("button");
const para = document.querySelector("p");

let countValue = 0;

function increment() {
  countValue++;
  para.textContent = `Click count: ${countValue}`;
}

const restart = document.querySelector("#restart");

function start() {
  restart.disabled = true;
  countValue = 0;
  para.textContent = "Click count: 0";
  btn
    .when("click")
    .take(5)
    .subscribe({
      next: increment,
      complete() {
        restart.disabled = false;
        para.textContent = `Count finished!`;
      },
    });
}

restart.when("click").subscribe(start);
start();

basic-take

Specifications

Browser compatibility

See also

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。