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

55 lines
1.0 KiB
Markdown
Raw Normal View History

# Run In Background
2016-03-26 00:47:20 +01:00
Run part of a program while the rest of it is doing something else.
2016-03-26 00:47:20 +01:00
2016-03-26 05:13:09 +01:00
```sig
2016-03-26 00:47:20 +01:00
control.inBackground(() => {
})
```
## ~hint
For more information, read
2016-11-02 01:44:37 +01:00
[The @boardname@ - a reactive system](/device/reactive).
It is pretty advanced!
## ~
## Example
2016-03-26 00:47:20 +01: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-26 00:47:20 +01:00
2016-03-26 05:13:09 +01:00
```blocks
2016-03-26 00:47:20 +01:00
let num = 0
control.inBackground(() => {
while (true) {
basic.showNumber(num)
2016-03-26 00:47:20 +01:00
basic.pause(100)
}
})
2020-02-20 17:00:11 +01:00
input.input.onButtonEvent(Button.A, ButtonEvent.Click, () => {
2016-03-26 00:47:20 +01:00
num++;
})
```
This program does the same thing, but in a more usual way,
with a ``forever`` loop.
2016-03-26 00:47:20 +01:00
2016-03-26 05:13:09 +01:00
```blocks
2016-03-26 00:47:20 +01:00
let num = 0
basic.forever(() => {
basic.showNumber(num)
2016-03-26 00:47:20 +01:00
})
2020-02-20 17:00:11 +01:00
input.input.onButtonEvent(Button.A, ButtonEvent.Click, () => {
2016-03-26 00:47:20 +01:00
num++;
})
```
## See also
2016-03-26 00:47:20 +01:00
[while](/blocks/loops/while), [forever](/reference/basic/forever),
[on button pressed](/reference/input/on-button-pressed)
2016-03-26 00:47:20 +01:00