Receive socket when in loop arduino (Interupt a while loop with a socket) I'm currently working on an arduino project. Were the arduino is communicating with a NodeJS server via web sockets.

The socket connection is working fine and has no problems. But the problem I currently have is that I want to be able interupt an infinite while loop with a socket emit from the NodeJS server.

I found a page that had a solution for this problem but only with a button attached to the arduino.

Link to page (Interrupt with button)

This is the loop I want to be able to interrupt with a socket:

bool loopRunning = true;

void rainbow(int wait) {
while(loopRunning == true) {

      for(long firstPixelHue = 0; firstPixelHue &lt; 3*65536; firstPixelHue += 256) {
        for(int i=0; i&lt;strip.numPixels(); i++) { 
          int pixelHue = firstPixelHue + (i * 65536L / strip.numPixels());
          strip.setPixelColor(i, strip.gamma32(strip.ColorHSV(pixelHue)));
        }
        strip.show(); 
        delay(wait);  
      }
    }
}


I want to set loopRunning to false when I recieve a socket emit.

Anyone have any ides how I can implement this?

Page to the socket functionality that I use
There are two ways to handle events: interrupts (hardware triggered) and polling (software triggered). Interrupts are much more efficient but also more difficult to use. SocketIoClient uses polling.

The necessary part of polling is... polling. That is, many times per second, you (or your library) needs to check if anything interesting is happening.

With this library, you have to call SocketIoClient::loop() many times a second. That's why SocketIoClient::loop() exists. So it needs to be added to your outer for loop.

(If your delay(wait) takes too long, you may need to break it up into a series of several shorter ones, but I think you can get away with it in this case.)

Then all you need to do is use SocketIoClient::on() to perform an action when an event happens. There is an example in the documentation. You will need to make loopRunning into a global variable.