0

I am working with the BBC Micro Bit and am creating an extension for Make Code in TypeScript.

I have the following event that gets triggered by a wheel encoder on my robot. Inside the event, I increment a couple of variables. In the Arduino language, I would declare such variables as "volatile" indicating that the variable could be changed by an interrupt, thus ensuring that I was working with the most recent value in the variable.

control.onEvent(EventBusSource.MICROBIT_ID_IO_P0, EventBusValue.MICROBIT_PIN_EVT_RISE, function () {
    _lTicks += 1;
    _lerrTicks += 1;
    if (_lTicks % _partialTurn == 0) {
        _lTicks = 0;
        _lTurns += .0625;
    }
})

Does TypeScript have an equivalent "volatile" keyword when declaring a variable? If so, how is it implemented?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Trevor Shaw
  • 123
  • 1
  • 10

1 Answers1

5

Javascript has no volatile because JavaScript run-times are single threaded. This means that there is is nothing to interrupt this code and no other code can change the state while the code runs.

Generally if an event occurs during the execution of a piece of code, that event will be put in a queue and code associated with the event will only be executed once the current code stack is done running.

Even things like WebWorkers which allow running multiple JS threads do not break this assumption. They instead rely on message passing between the two threads without allowing for shared variables.

Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357