/*
  Etwas laufen lassen nur wenn man es benötigt:
  https://forum.arduino.cc/t/mqtt-schleife-vorzeitig-unterbrechen/1170641/8
  2023-09-22 by noiasca
  code in sketch
*/

bool looprunning = true;

void setup() {
  Serial.begin(115200);
}

void loop() {
  //loopme();
  runNonBlocking();
}

void runNonBlocking() {
  if (looprunning == true) {
    static uint32_t previousMillis = 0;  // store timestamp
    static uint8_t i = 0;                // the iteration counter (old: i from for)
    const uint8_t iMax = 10;             // max iterations
    const uint16_t intervalShort = 100;  // old "delay(100)"
    const uint16_t intervalLong = 1000;  // old "delay(1000)"
    uint16_t interval = intervalShort;   // current interval
    if (i == 0)
      interval = intervalLong;
    if (millis() - previousMillis > interval) {
      previousMillis = millis();
      Serial.print("Counter: ");
      Serial.println(i);
      if (i == iMax) i = 0; else i++;
    }
  }
}

void loopme() {
  if (looprunning == true) {
    for (int i = 0; i < 11; i++)
    {
      Serial.print("Counter: ");
      Serial.println(i);
      delay(100);
    }
    delay(1000);
  };
}