Curious what Dynamic People can do for you?

+ 31 (0) 20 303 24 70
Tech Blogs
16 December 2019 Sebastian Goy

A while / do-until loop in PowerApps?


PowerApps brings us a lot of new possibilities. In a blog serie Dynamic People consultant Sebastian Goy will guide you through some functionality. This article provides a short explanation on how a ‘while’ or ‘do until’ loop can be mimicked in Power Apps.

For those unfamiliar, Wikipedia explains that a while-loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement.

Power Apps has a ‘looping’ expression in ForAll which evaluates a formula for all records of a table, and whilst this covers some of the use-cases a while or do-until loop would solve there are still many scenario in which it doesn’t. So let’s dive in and find out how to ‘while loop’ in Power Apps.

How to

To start place a control that can trigger a behavioral expression, for this example a Button will be used.

In the Button.OnSelect add the two following expressions:

UpdateContext({varRuns: 0});

UpdateContext({varStartTimer: true})

These two context variables serve as the trigger and counter variables for the loop, there is one more element missing though which is the ‘end condition’. Place a TextInput and set the TextInput.OnChange to:

UpdateContext({varLoopEnd: Value(TextInput.Text)})

Set the TextInput.Default to varLoopEnd

Now for the secret sauce of the Power Apps while loop, which is the Timer control.

Place a Timer control onto the screen and set Timer.Duration to 1000. This is for the demo only, depending on the expression(s) you would like to loop this timer should be set as small as possible. Change the Timer.Start to varStartTimer, this will cause the Button.OnSelect to start the timer.  Now set the Timer.Repeat to:

If(varRuns >= varLoopEnd – 1, false, true)

We’re almost there, set the Timer.OnTimerEnd to

// Insert the expressions and you would like the loop to execute here
UpdateContext({varRuns: varRuns + 1});

If(varRuns >= varLoopEnd – 1, UpdateContext({varTimerStart: false}))

PowerApps WhileLoop

So what happens here in words?

Entering a value in the TextInput will set the LoopEnd condition, there could however be many ways to construct this and as long as it evaluates into a Boolean and is placed in the Timer.Repeat. You could for example loop over a collection and look for a certain condition.

When a value is entered and the Button is pressed the Timer starts, it runs for the duration and at the end triggers the Timer.OnTimerEnd expressions. It executes your custom added expressions, after which it adds a ‘run’ and evaluates whether it should reset the trigger for the loop (not the loop itself!).

Then Timer.Repeat is evaluated, if it evaluates to false the loop stops, if it evaluates to true another run is started.

And that’s it…!