2016-06-24 19:25:47 +02:00
|
|
|
# Run In Background
|
2016-03-26 00:47:20 +01:00
|
|
|
|
2016-06-24 19:25:47 +02: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(() => {
|
|
|
|
})
|
|
|
|
```
|
|
|
|
|
2019-12-02 05:58:26 +01:00
|
|
|
## ~hint
|
2016-06-24 19:25:47 +02:00
|
|
|
|
|
|
|
For more information, read
|
2016-11-02 01:44:37 +01:00
|
|
|
[The @boardname@ - a reactive system](/device/reactive).
|
2016-06-24 19:25:47 +02:00
|
|
|
It is pretty advanced!
|
|
|
|
|
2019-12-02 05:58:26 +01:00
|
|
|
## ~
|
2016-06-24 19:25:47 +02:00
|
|
|
|
2019-12-02 05:58:26 +01:00
|
|
|
## Example
|
2016-03-26 00:47:20 +01:00
|
|
|
|
2016-06-24 19:25:47 +02: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) {
|
2019-12-02 05:58:26 +01:00
|
|
|
basic.showNumber(num)
|
2016-03-26 00:47:20 +01:00
|
|
|
basic.pause(100)
|
|
|
|
}
|
|
|
|
})
|
2023-01-11 18:51:27 +01:00
|
|
|
input.onButtonEvent(Button.A, input.buttonEventValue(ButtonEvent.Down), () => {
|
2016-03-26 00:47:20 +01:00
|
|
|
num++;
|
|
|
|
})
|
|
|
|
```
|
|
|
|
|
2016-06-24 19:25:47 +02:00
|
|
|
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(() => {
|
2019-12-02 05:58:26 +01:00
|
|
|
basic.showNumber(num)
|
2016-03-26 00:47:20 +01:00
|
|
|
})
|
2023-01-11 18:51:27 +01:00
|
|
|
input.onButtonEvent(Button.A, input.buttonEventValue(ButtonEvent.Down), () => {
|
2016-03-26 00:47:20 +01:00
|
|
|
num++;
|
|
|
|
})
|
|
|
|
```
|
|
|
|
|
2019-12-02 05:58:26 +01:00
|
|
|
## See also
|
2016-03-26 00:47:20 +01:00
|
|
|
|
2016-06-24 19:25:47 +02: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
|
|
|
|