# While Loop

Source: https://docs.scrappey.com/docs/while-loop

> Repeat a set of browser actions until a specific condition is no longer true.

## Command

`"while"`

Use this command to perform looping logic within the browser context. It's useful for tasks like handling CAPTCHAs, paginated scraping, or waiting for content to disappear/appear.

## Parameters

| Parameter     | Type    | Required | Description                                                                                                   |
| ------------- | ------- | -------- | ------------------------------------------------------------------------------------------------------------- |
| `condition`   | string  | Yes      | A JavaScript expression that returns `true` or `false`. The loop continues as long as it evaluates to `true`. |
| `then`        | array   | Yes      | Array of browser actions to execute on each iteration while the condition is true.                            |
| `maxAttempts` | number  | No       | Max number of loop iterations to prevent infinite loops.                                                      |

## Example

```bash
curl -X POST "https://publisher.scrappey.com/api/v1?key=YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "cmd": "request.get",
    "url": "https://example.com",
    "browserActions": [
      {
        "type": "while",
        "condition": "document.querySelector('body').innerText.toLowerCase().includes('terms')",
        "then": [
          {
            "type": "goto",
            "url": "https://example.com/alternate-page"
          },
          {
            "type": "solve_captcha",
            "captcha": "turnstile"
          }
        ]
      }
    ]
  }'
```

## Notes

* You can combine this with other browser actions like `click`, `type`, `goto`, `wait`, or even another `if` or `while` block.
* Always consider setting a `maxAttempts` to avoid infinite loops and excessive resource usage.
* Use Case Ideas: looping through paginated content until no "Next" button appears, retrying CAPTCHA solving until successful, or waiting for an element to disappear before proceeding.
