← Back to Docs

while Loops

while repeats a block of code as long as a condition is true.

⚠️ Loop Protection

By default, VDX blocks loops that iterate faster than 2 seconds. See Loop Protection and @unsafe.

Syntax

while (condition) {
    // body
}

Example with wait

To satisfy the loop protection, use wait() to slow each iteration to at least 2 seconds:

class App {
    let i = 5;
    while (i > 0) {
        print("countdown:", i);
        i = i - 1;
        wait(2100);
    }
    print("done!");
}

Fast loops with @unsafe

If you need a fast loop, use @unsafe:

class App {
    let i = 0;
    @unsafe while (i < 100) {
        print(i);
        i = i + 1;
    }
}

Loop with function

class App {
    fn countdown(n) {
        @unsafe while (n > 0) {
            print(n);
            n = n - 1;
        }
    }

    countdown(5);
}

Scoping

Variables declared inside a while block are local to that iteration. See Scoping Rules.