Home Examples Docs
7. Loops in targets
Targets are equipped with a built-in looping mechanism, making explicit loop statements rarely necessary. Additionally, loops can be slowed down using the interval property, which inserts a pause between each iteration. One key advantage of target-based loops is that they automatically wait for any imperative targets to complete before proceeding to the next iteration. Loops can be implemented in several ways:
1. loop
Enabling the loop property will cause the value function to be called indefinitely. prevTargetValue refers to the value of the previous target, which, in this case, is html:
Rewriting the example above using only a declarative target:
We can also implement the loop as a function to limit its execution. In the example below, we limit it to 100 iterations:
We can also slow down the loop using the interval property. In the following example, the html target is updated once every 500 ms:
2. Reactive targets and activateTarget
We can use reactive targets and call activateTarget in the final target to reactivate the first target in the sequence, creating a continuous execution loop.
3. onComplete
onComplete is called when a target fully completes its task. In this example, width iterates through a list of values. When it finishes, onComplete is executed to reactivate the width target, creating an indefinite loop. The height$ target reacts to the width values, as it ends by a single $ suffix.
4. Cycles
The final method of iteration is using Cycles:
We can slow the iteration by adding an interval property. In the following example, we set the cycles to 5 and the interval to 1000. We also set the loop to true, which makes the cycle restart from zero each time it reaches 5.
In the following example, we set an imperative target within the value, which takes one second to execute. The cycle will only update once all the imperative targets defined within that target are completed. When combined with an interval, the cycle will update after the longest duration.
In the last following example, it illustrates combining cycles with steps. The value() function returns the cycle as the target, and the actual value steps through 10 times. Notice that the interval is applied both when calling the value and during each step.