pxt-calliope/docs/reference/control/in-background.md

55 lines
990 B
Markdown
Raw Normal View History

# Run In Background
2016-03-25 16:47:20 -07:00
Run part of a program while the rest of it is doing something else.
2016-03-25 16:47:20 -07:00
2016-03-25 21:13:09 -07:00
```sig
2016-03-25 16:47:20 -07:00
control.inBackground(() => {
})
```
## ~hint
For more information, read
2016-11-01 17:44:37 -07:00
[The @boardname@ - a reactive system](/device/reactive).
It is pretty advanced!
## ~
## Example
2016-03-25 16:47:20 -07:00
This program shows how running in the background can say what is
stored in a variable like `num`, while another part (``on button pressed``)
changes what is stored there.
2016-03-25 16:47:20 -07:00
2016-03-25 21:13:09 -07:00
```blocks
2016-03-25 16:47:20 -07:00
let num = 0
control.inBackground(() => {
while (true) {
basic.showNumber(num)
2016-03-25 16:47:20 -07:00
basic.pause(100)
}
})
2020-08-19 22:03:58 +02:00
input.onButtonPressed(Button.A, () => {
2016-03-25 16:47:20 -07:00
num++;
})
```
This program does the same thing, but in a more usual way,
with a ``forever`` loop.
2016-03-25 16:47:20 -07:00
2016-03-25 21:13:09 -07:00
```blocks
2016-03-25 16:47:20 -07:00
let num = 0
basic.forever(() => {
basic.showNumber(num)
2016-03-25 16:47:20 -07:00
})
2020-08-19 22:03:58 +02:00
input.onButtonPressed(Button.A, () => {
2016-03-25 16:47:20 -07:00
num++;
})
```
## See also
2016-03-25 16:47:20 -07:00
[while](/blocks/loops/while), [forever](/reference/basic/forever),
[on button pressed](/reference/input/on-button-pressed)
2016-03-25 16:47:20 -07:00