ABC of Electronics cosycom.com
ARDUINO 18 · Timing

Arduino Timing: millis() vs delay()

Why delay() quietly freezes your entire sketch, and how millis() lets you time things while everything else keeps running.

You'll need: two LEDs on separate pins (try 8 and 9), each with its own resistor.

delay(ms), used throughout the earlier lessons, does exactly what it says — but it does so by completely halting the sketch for that entire duration, including digitalRead() calls, serial input, everything. A button pressed during a delay() is simply missed. This is fine for a single blinking LED, but breaks down the moment you want two things happening on independent schedules.

unsigned long previousTime = 0;
const long interval = 1000;
bool ledState = false;

void setup() {
  pinMode(8, OUTPUT);
}

void loop() {
  unsigned long currentTime = millis();

  if (currentTime - previousTime >= interval) {
    previousTime = currentTime;
    ledState = !ledState;
    digitalWrite(8, ledState);
  }
  // loop() keeps running immediately -- nothing here is frozen
}

millis() returns the number of milliseconds since the board last powered on or reset, continuously counting up in the background, with no waiting involved. Instead of pausing, this pattern checks, on every single pass through loop(), whether enough time has elapsed since the last action — and only then does something, updating previousTime to restart the countdown. Everything else in loop() keeps running freely between those checks.

As an exercise, add a second identical block for pin 9 with a different interval, like 300ms — with delay() this would be awkward at best; with the millis() pattern, both LEDs blink independently, at their own separate rates, in the very same sketch.

abcofelectronics
millis() keeps counting A steadily rising count in the background, checked (not waited on) each pass through loop() — the basis of non-blocking timing.
TRY THIS
delay() freezes the whole sketch for its duration; millis() lets you time an action while everything else in loop() keeps running normally.