Caution:clearInterval() - with no arguments - is most likely fatal to any of your code... because it clears every set interval in the whole system. Therefore - when you need to clear a set interval you hold on to the hanndle return by the setting and use that handle for the clearing:
var iId = setInterval(D2.toggle.bind(D2), 500);
To stop the blinking you code:
clearInterval(iId);
This blinker thing has though an issue: the LED / Pin may stay on or off depending when it get's stopped. Therefore, you may think about this:
clearInterval(iId); D2.write(0); // stop blinking and turn LED off
(.write(0) is assuming hat .write(1) turns the LED on; otherwise: you just use .write(1)).
The next issue with this blinker thing is that it turns the LED on for the first time after the first interval has passed. Therefore you also enhance the setup with:
var iId = setInterval(D2.toggle.bind(D2), 500); D2.write(1);
('Some' will now speak up and say: the first blink will be shorter than the others... yep. If you 'turn it around' and turn LED on before setting up the interval for toggling, the first blink will be longer than the others... But both matter only when interval time is gets close to the time to execute code for either turning the LED on and setting up the interval, respective. Either way, if this this the case, the LED still blinks but not for the human eye.)
There is more to this blink thing,... (may be in another post or conversation).
PS: I used the fat arrow function to tidy the code.
Espruino is a JavaScript interpreter for low-power Microcontrollers. This site is both a support community for Espruino and a place to share what you are working on.
Caution:
clearInterval()
- with no arguments - is most likely fatal to any of your code... because it clears every set interval in the whole system. Therefore - when you need to clear a set interval you hold on to the hanndle return by the setting and use that handle for the clearing:To stop the blinking you code:
This blinker thing has though an issue: the LED / Pin may stay on or off depending when it get's stopped. Therefore, you may think about this:
(
.write(0)
is assuming hat.write(1)
turns the LED on; otherwise: you just use.write(1)
).The next issue with this blinker thing is that it turns the LED on for the first time after the first interval has passed. Therefore you also enhance the setup with:
('Some' will now speak up and say: the first blink will be shorter than the others... yep. If you 'turn it around' and turn LED on before setting up the interval for toggling, the first blink will be longer than the others... But both matter only when interval time is gets close to the time to execute code for either turning the LED on and setting up the interval, respective. Either way, if this this the case, the LED still blinks but not for the human eye.)
There is more to this blink thing,... (may be in another post or conversation).
PS: I used the fat arrow function to tidy the code.