I have an express app running socket.io on my raspberry pi which is controlling an LED panel. To drive the panel I have a while loop that is constantly updating the pixels in the panel. I want to be able to change the parameters of that loop or switch to a different loop altogether to control what animation the panel is displaying.
What is the best way to do this? When I have tried just passing a new socket.io message to the server the message isn't received because it is blocked by the loop. I can start the first animation this way but any subsequent messages are blocked.
I can provide code snippets if needed.
Instead of a loop, use a function that calls itself asynchronously at the end. This allows events like socket.io messages to be handled before the next function execution.
The HTML page below illustrates the idea. The loop increments a counter every second and by pressing the button, you can increase the increment.
<!DOCTYPE html><html>
<head>
<script type="text/javascript">
var counter = 0, increment = 1;
function loop() {
counter += increment;
document.querySelector("span").textContent = counter;
setTimeout(loop, 1000);
}
</script>
</head>
<body onload="loop()">
<span></span>
<button onclick="increment++">Count faster</button>
</body>
</html>
Here, setTimeout(loop) is "sufficiently asynchronous" to allow click events, whereas Promise.resolve().then(loop) would not be. As the comment below says, your code is needed for a judgment how it works for your events.