> For the complete documentation index, see [llms.txt](https://docs.gpmautomate.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.gpmautomate.com/automate-zh/action-shi-yong-zhi-nan/blocks/while.md).

# While

与 For 循环（以固定次数循环）不同，While 循环通常用于当您事先不知道脚本需要重复多少次，而完全取决于运行时的实际状态的情况。

🎥 观看更多教程视频：[点击这里](https://youtu.be/4O4dPC-CNHM)。

#### 工作原理：

* 在每次循环开始之前，系统会检查您配置的条件（Condition）。
* 如果条件尚未满足，While 语句块内的操作将继续执行。
* 一旦条件满足，系统将停止循环，并转到 While 语句块下方的后续操作。

#### 实际案例：等待获取 Mail/Telegram 的 OTP 验证码

假设您正在制作账号注册脚本，需要等待系统将 OTP 验证码发送到邮箱。由于邮件到达的时间可能快也可能慢，您无法提前知道需要等待多久：

* 您将 Read mail code 操作放入 While 语句块中。
* 循环的停止条件：当变量 `$otpCode` 获得值（不再为空）时。
* 系统将不断检查并读取邮箱。一旦成功获取到 OTP 验证码，条件满足，循环停止，脚本继续执行填写验证码的步骤。

<figure><img src="/files/dAKiUvMThZloy24KyP5S" alt=""><figcaption></figcaption></figure>

> ⚠️ 重要提示：使用 While 循环时，您需要确保语句块内的操作会改变停止条件的状态。如果条件配置错误，或邮件永远不会到达，脚本将陷入无限循环（脚本卡死）的状态。
>
> 为了优化，您应该额外结合一个用于记录检查次数的变量。如果超过 10 次仍没有收到邮件，请使用 Exit loop 操作退出循环，或使用 Stop 操作彻底停止程序并转到下一个 profile。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.gpmautomate.com/automate-zh/action-shi-yong-zhi-nan/blocks/while.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
