🌐
DigiKey
digikey.com › en › maker › tutorials › 2022 › how-to-avoid-using-the-delay-function-in-arduino-sketches
How to Avoid Using the Delay() Function in Arduino Sketches
February 23, 2022 - The delay() function allows you to pause the execution of your Arduino program for a specified period. For that purpose, the method requires you to supply it with a whole number that specifies how many milliseconds the program should wait.
🌐
Arduino Forum
forum.arduino.cc › projects › programming
Generalization question: Wait with millis() instead of delay() all the time? - Programming - Arduino Forum
February 2, 2021 - [!SOLVED! Issue: coding error, wrong variable used for math which resulted in 0 wait time 🙂 Lesson learned: delay() doesn't interrupt anything, especially not servo motion, even though doc suggests it does ] hey guys, Story: My servo didn't "reset" to 0 position even though I used delay() to wait for it to happen.
Discussions

PSA: You're probably using delay() when you want to use millis().
If you're lazy ellapsedMillis also works really well. To my eyes it also results in more easily readable code, I use it a lot. More on reddit.com
🌐 r/arduino
53
363
May 23, 2023
Wait() or delay() | MySensors Forum
Waiting using the Arduino delay() command is not a good idea. It halts all MySensors processing and should be avoided. More on forum.mysensors.org
🌐 forum.mysensors.org
4
0
March 2, 2016
programming - Is there any better choice other than using delay() for a 6-hours delay? - Arduino Stack Exchange
Using delay() for a 6-hour delay is a bit awkward, but perfectly doable. It will, however, not be very accurate, because the accuracy depends on the accuracy of the Arduino's clock, and it will block all other code you may wish to run. Using timing with millis() would allow your Arduino to do other things while waiting... More on arduino.stackexchange.com
🌐 arduino.stackexchange.com
December 13, 2020
Alternatives to delay()
hi, just built my first project with Arduino. Was hoping to optimize it in a few ways (reduce global variables, lesser string variables etc.) when i stumbled upon a few posts saying that delay() was for beginners and that millis() was more useful when multi-tasking... although using either ... More on forum.arduino.cc
🌐 forum.arduino.cc
5
0
August 10, 2023
🌐
Arduino Forum
forum.arduino.cc › projects › programming
Delay/Pause/Wait ??? - Programming - Arduino Forum
October 10, 2014 - Hi all, I am a newbie to C++ and Arduino so have a small project but am not sure how best to tackle it. Basically I have a Mega board and will put 2x PIR sensors on it and then output to a 2x Relay board. These will be i…
🌐
Arduino
docs.arduino.cc › language-reference › en › functions › time › delay
delay() | Arduino Documentation
9 delay(1000); // waits for a second (1000 ms) 10 digitalWrite(ledPin, LOW); // sets the LED off · 11 delay(1000); // waits for a second (1000 ms) 12} While it is easy to create a blinking LED with the · delay() function, and many sketches use short delays for tasks such as switch debouncing, the use of ·
🌐
Random Nerd Tutorials
randomnerdtutorials.com › home › arduino › theory and blog › why you shouldn’t always use the arduino delay function
Why You Shouldn’t Always Use the Arduino Delay Function | Random Nerd Tutorials
April 2, 2019 - Though I have to send one time the data to switch on the relay from channel 1, as an example , for 50 miliseconds, than the relay stays on to switch on the valve for 20 min, than the Arduino must send again the same signal for 50 msec to switch of ch 1 (relay 1) wait (100 msec) and switch on ch 2 (50 msec) with an other data code. This are al ready 5 delays this would be verry easy bud not with “millis” I dont like to waist my time with this !
🌐
Reddit
reddit.com › r/arduino › psa: you're probably using delay() when you want to use millis().
r/arduino on Reddit: PSA: You're probably using delay() when you want to use millis().
May 23, 2023 -

One of the most frequent recommendations I make when auditing Arduino code comes to the difference in use cases for millis() and delay(). This little blurb should help you to differentiate the two and understand why you would use one over the other.

First, millis() is an essential function in programming that returns the elapsed time in milliseconds since the board began running the current program. Unlike other timing functions, millis() is non-blocking, meaning it does not interrupt the flow of your program. Instead, it allows you to check the passage of time at any point in your program. This is particularly useful in scenarios requiring simultaneous tasks or tasks at varying intervals. For instance, if you're operating an LED light while gathering sensor data at different intervals, millis() allows you to do both independently.

Blinking Light Example:

#define LED_PIN LED_BUILTIN
#define BLINK_INTERVAL 1000  // Blink every 1000 ms (1 second)

unsigned long previousMillis = 0;
bool ledState = LOW;

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

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

  if (currentMillis - previousMillis >= BLINK_INTERVAL) {
    previousMillis = currentMillis;  // Remember the time

    ledState = !ledState;            // Toggle the LED state
    digitalWrite(LED_PIN, ledState);
  }
}

While it may require a bit more complexity in the code to store timestamps and check time differences, the benefits of non-blocking multitasking outweigh this additional complexity.

It's sibling, delay(), is used to pause the execution of the current program for a specified number of milliseconds. Unlike millis(), delay() is a blocking function, meaning it stops all other operations on the board for the duration specified. For example, if you are blinking an LED and use delay(1000), the LED will turn on, the program will pause for one second, and then the LED will turn off. While delay() is a simpler and more straightforward function to use, it is best suited to simpler tasks that do not require multitasking.

Blinking Light Example:

#define LED_PIN LED_BUILTIN

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

void loop() {
  digitalWrite(LED_PIN, HIGH);  // Turn the LED on
  delay(1000);                  // Wait for a second
  digitalWrite(LED_PIN, LOW);   // Turn the LED off
  delay(1000);                  // Wait for a second
}

If the task is time-sensitive or requires simultaneous operations, delay() might not be the best option due to its blocking nature.

I hope this clears up the "why" of each! Please ask any questions

🌐
Github
eduherminio.github.io › blog › delay-function-is-not-your-friend
Waiting in Arduino I: delay() function is not your friend | eduherminio.github.io
September 6, 2020 - No, absolutely no (and whoever tells you the opposite is a liar 😛). As in any other programming language, each Arduino program/sketch has a very concrete purpose, which in this case is serving as ‘Hello, world!’ or welcoming sample for beginners. That example uses the delay() function in order to wait for things to happen for the sake of simplicity, but that’s in general not a good pattern to follow.
🌐
Norwegian Creations
norwegiancreations.com › 2017 › 09 › arduino-tutorial-using-millis-instead-of-delay
Arduino Tutorial: Using millis() Instead of delay() – Norwegian Creations
September 5, 2017 - With delay() this is not possible since we do not know how long the loop execution time is. Accurate timing like this is very useful when sampling at a certain frequency or running filters, among other things. The other advantage with millis() is that it won’t prevent us from running code while “waiting”.
Find elsewhere
🌐
Adafruit
learn.adafruit.com › multi-tasking-the-arduino-part-1 › ditch-the-delay
Ditch the delay() | Multi-tasking the Arduino - Part 1 | Adafruit Learning System
November 3, 2014 - Timing with delay() is simple and straightforward, but it does cause problems down the road when you want to add additional functionality. The problem is that delay() is a "busy wait" that monopolizes the processor.
🌐
MySensors Forum
forum.mysensors.org › home › development › wait() or delay()
Wait() or delay() | MySensors Forum
March 2, 2016 - A reason for asking, is that delay() is used in a number of examples... these should all be changes to wait().. wait() is never used in any of the examples... also, process() is NOT uses in any examples, this should be added to the loop function as a proper way to implement a loop... ... Yes, still found in a couple of examples. Should be removed (unless they are used because no messages should be processed). https://github.com/mysensors/Arduino/search?utf8=✓&q=delay++path:/libraries/MySensors/examples/&type=Code
🌐
Programming Electronics Academy
programmingelectronics.com › home › delay() arduino function: tight loops and blocking code
delay() Arduino Function: Tight Loops and Blocking Code - Programming Electronics Academy
April 2, 2019 - Let’s take our program and get rid of delay, but we’ll add a for loop. Our for loop will print out numbers and text to the serial port. So how long does this loop run for? It’s going to run for a while because it has to go through 100 iterations before it stops. And what about the code after this for loop? Is it able to run? No, it has to wait because it’s being blocked by the for loop.
Top answer
1 of 5
9

Several options here, and a couple folks have pointed out some challenges.

"Best" answer -- probably to use a real-time clock (RTC) board to assist your timing, and effectively set a target time (next motor run is at 23:14...) each time the cycle restarts. By saving this target off (to the EEPROM or an SD card for instance), you'd protect against a potential shutdown and reset of the arduino in the middle.

Secondary answer; set your loop() to include a relatively short delay() statement, then check the elapsed time since the last motor engagement. This would allow you to have other items processing, as someone else noted in this thread. This I've pseudocoded below.

unsigned long lastMotorRunTime;

void loop()
{
    /*
     * do whatever 
     */
    if(millis()-lastMotorRunTime > 21600000)  // 6 hours have passed
    {
         runTheMotor(); // placeholder for the motor movements you need
         lastMotorRunTime = millis();
    }
   /* 
    * do other stuff 
    */
   delay(100); // loop about every 1/10 second, or whatever works
}

Given you don't seem to need detailed precision -- a few seconds either way wouldn't matter -- this should work reasonably. Note it WILL fail if the Ardiuno is reset -- then it will only (in my pseudocode) rotate the motor 6 hours after the last Arduino reset. Probably better to assume that an arduino reset means move the motor 'now', if the point is to ensure periodic motion rather than precise timing.

For precise timing, as noted, the RTC would be required.

(Updated: Changed lastMotorRunTime to unsigned long)

2 of 5
3

Since this is for an incubator, I suspect that you don't need high precision. So delay() will work perfectly well, if you don't want to do anything else in the meantime (like maybe monitor temperature, control a heater, and/or light LEDs for over/under temperature). In that case you could use a loop that handled all those operations at some convenient rate like once per second or once per minute, using delay() in the loop. (I assume that your incubator is slow to respond to the heater, so slow sampling will be fine.) Then let the loop run for 6 hours, which you can determine by simple count of the 1-minute (or whatever) loop delays. And if you find that your 6-hour time is consistently high or low, adjust the count limit to compensate.

🌐
DeepBlue
deepbluembedded.com › home › blog › arduino delay() function tutorial
Arduino delay() Function Tutorial
July 26, 2025 - delay() is a function used to insert time delay between events in Arduino. It keeps the CPU blocked waiting for a specific period of time (in ms unit).
🌐
Arduino Forum
forum.arduino.cc › projects › general guidance
Alternatives to delay() - General Guidance - Arduino Forum
August 10, 2023 - hi, just built my first project with Arduino. Was hoping to optimize it in a few ways (reduce global variables, lesser string variables etc.) when i stumbled upon a few posts saying that delay() was for beginners and that millis() was more useful when multi-tasking... although using either ...
Top answer
1 of 2
4

There is no absolute need for any Arduino program to use delay()

The blink without delay sketch that is included in the standard sketch examples is the canonical illustration of this.

In most cases you don't need to poll your sensors thousands of times a second. It is good discipline to only poll sensors as often as makes sense for the specific application. Sometimes this might be once every five minutes. For example an ambient temperature sensor. In those cases there is nothing to be gained be polling a thousand times a second. To do so wastes resources and is a poor habit that could be troublesome for battery powered applications.

For example, the use of millis() for timing allows you to effectively poll several peripherals each at different intervals, perhaps averaging some readings to reduce noise, perhaps also updating a display at other intervals that suit human perception.

For long running battery powered applications it is likely that you will benefit from finding out about putting the microcontroller to sleep using sleep() or deepSleep() and using interrupts to wake it. A real time clock (RTC) or the watchdog timer interrupt can perhaps be used to schedule your sensor readings and other actions, perhaps in conjunction with millis().

For very simple programs that don't need precise timings. delay() can be the simplest and clearest way to manage timings.

2 of 2
1

No, there is no need to use delay() at all. Unlike the sleep() or deepSleep() commands, delay does not save power or do anything else that's special.

The standard implementation of delay is just doing a busy-wait until the time has elapsed, something like:

void delay(int ms)
{
    int end = millis() + ms;
    while (millis() < end) {}; // do nothing
}

So for the CPU itself, this just wastes CPU cycles, it doesn't save any power.

🌐
TutorialsPoint
tutorialspoint.com › arduino › arduino_delay_function.htm
Arduino - delay () function
Arduino - Discussion · Selected Reading · UPSC IAS Exams Notes · Developer's Best Practices · Questions and Answers · Online Resume Builder · HR Interview Questions · Computer Glossary · Who is Who · Previous · Quiz · Next · The way the delay() function works is pretty simple. It accepts a single integer (or number) argument. This number represents the time (measured in milliseconds). The program should wait until moving on to the next line of code when it encounters this function.
Top answer
1 of 2
2
In-depth explanation of delay() VS millis() in Arduino:What is delay()?The delay(ms) function is a simple way to pause your program for a specific duration (in milliseconds). While using delay(), the microcontroller does nothing except wait, effectively blocking all other code execution.Example: Blinking an LED using delay()Here’s a basic example of using delay() to blink an LED every second: const int ledPin = 13; void setup() { pinMode(ledPin, OUTPUT); } void loop() { digitalWrite(ledPin, HIGH); // Turn LED on delay(1000); // Wait for 1 second digitalWrite(ledPin, LOW); // Turn LED off delay(1000); // Wait for 1 second } This works, but there's a major drawback: nothing else can run while delay() is active. If you need to read a sensor, receive serial input, or perform another task during the delay, it won’t be possible. What is millis()?The millis() function returns the number of milliseconds since the Arduino board was powered on or reset. Unlike delay(), millis() does not stop program execution. Instead, it allows you to track elapsed time while still performing other tasks.Example: Blinking an LED without delay() using millis()Instead of stopping everything for a delay, we can check if enough time has passed and then toggle the LED. const int ledPin = 13; unsigned long previousMillis = 0; // Store the last time LED was updated const long interval = 1000; // Blink interval (1 second) void setup() { pinMode(ledPin, OUTPUT); } void loop() { unsigned long currentMillis = millis(); // Get the current time // Check if 1000ms (1 second) has passed since the last LED update if (currentMillis - previousMillis >= interval) { previousMillis = currentMillis; // Save the last time LED changed state digitalWrite(ledPin, !digitalRead(ledPin)); // Toggle LED state } }   In this example:The LED toggles every second without blocking the loop. Other code can run simultaneously, such as reading sensors, handling inputs, or controlling motors. When should you use millis() instead of delay()?You should use millis() when:1. You need to run multiple tasks at once (e.g., read sensors while controlling LEDs).2. You need a responsive program that can handle inputs in real time.3. You want to avoid blocking the execution of other parts of the code.4. You are working with interrupts, communication protocols, or multitasking logic.delay() is only suitable for very simple programs where no other tasks need to run during the wait time.Multitasking with millis()Let’s say we want to:1. Blink an LED every 1 second.2. Read a button press every 100ms.3. Print a message every 2 seconds.Using millis(), we can handle all three tasks without blocking execution: const int ledPin = 13; const int buttonPin = 2; unsigned long previousLedMillis = 0; unsigned long previousButtonMillis = 0; unsigned long previousMessageMillis = 0; const long ledInterval = 1000; const long buttonInterval = 100; const long messageInterval = 2000; void setup() { pinMode(ledPin, OUTPUT); pinMode(buttonPin, INPUT_PULLUP); Serial.begin(9600); } void loop() { unsigned long currentMillis = millis(); // Blink LED every 1 second if (currentMillis - previousLedMillis >= ledInterval) { previousLedMillis = currentMillis; digitalWrite(ledPin, !digitalRead(ledPin)); } // Check button state every 100ms if (currentMillis - previousButtonMillis >= buttonInterval) { previousButtonMillis = currentMillis; if (digitalRead(buttonPin) == LOW) { Serial.println("Button Pressed!"); } } // Print a message every 2 seconds if (currentMillis - previousMessageMillis >= messageInterval) { previousMessageMillis = currentMillis; Serial.println("Hello from Arduino!"); } } This allows everything to run independently without interference, making the code much more efficient and responsive.
2 of 2
0
Great question! This is something a lot of people new to Arduino run into. Here’s a simple breakdown: delay() pauses the entire program for the specified amount of time (in milliseconds). So, if you use delay(1000), your Arduino will do nothing for 1 second. This is fine for very simple tasks, like blinking an LED. millis(), on the other hand, doesn’t stop the program. It simply returns the number of milliseconds that have passed since the Arduino was powered on or reset. You can use it to keep track of time without pausing the rest of your code. When to use each: Use delay() if your program only has one task and you don’t mind it pausing everything else (e.g., blinking an LED with nothing else happening). Use millis() when you need your code to be non-blocking. This is essential for projects that involve multiple tasks happening simultaneously (e.g., reading a sensor while controlling an LED). Let me know if you need an example code for better clarity!
🌐
Arduino Forum
forum.arduino.cc › projects › programming
delay, but without delay. - Programming - Arduino Forum
June 24, 2020 - So I was doing some research online, and I looked at "while", and I believe that it is a suitable replacement for delay, without pausing everything else on the board while(millis() < millis() + 1000){} // this while sho…
🌐
GitHub
gist.github.com › ZiTAL › 3c54be6310e57c90aed6
arduino: wait, function to replace delay · GitHub
arduino: wait, function to replace delay. GitHub Gist: instantly share code, notes, and snippets.