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

55 lines
1004 B
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!
### ~
2016-03-26 00:47:20 +01:00
### Example
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, 150)
basic.pause(100)
}
})
input.onButtonPressed(Button.A, () => {
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, 150)
})
input.onButtonPressed(Button.A, () => {
2016-03-26 00:47:20 +01:00
num++;
})
```
### See also
[while](/blocks/loops/while), [forever](/reference/basic/forever),
[on button pressed](/reference/input/on-button-pressed)
2016-03-26 00:47:20 +01:00