Exit loop if button is pushed

Im trying to change the LED pattern of my project with a push of a button.

here is the code:

buttonstate = digitalRead(button);
if(buttonstate == HIGH && previousbuttonstate == LOW){
 state = 1 - state;
 delay(100);
 {
previousbuttonstate = buttonstate;
if(state == 1){
 for( int i = 13; i >= 10; i--;){
 digitalWrite(LED, HIGH);
 delay(3000);
 digitalWrite(LED, LOW);
 {
 if(state == 0){
 for(int i = 10; i <= 13; i++;){
 digitalWrite(LED, HIGH);
 delay(3000);
 digitalWrite(LED, LOW);
 {

it functions perfectly when delay is set to at least 250ms. but when I set the delay to 250ms and above like the code above. The LED pattern wont change in an instant when button is pushed. I have to hold the button for at least 1-3 sec for the pattern to change. What I noticed is the loop must be finished first before it I can change the pattern. So I have to time it for when the last LED will light up that is where I will push the button to change the pattern.
I want to change the pattern in an instant if button is pushed. How can I achieve this? or is there something wrong with my code?

The blink without delay example in the IDE (File, Examples, Digital) or Robin2's several things at a time post will show how to do timing in a non blocking fashion so your sketch can respond quickly.

What if I want to read data and display it on the LCD with a 3 sec delay. When button is pushed program will immediately exit the loop where it reads data and display a different text for example a menu state where I can read the previous reading. How can I change the display without holding the button for too long?

See reply #1

Like others have already answered: check out the “Blink without delay” tutorial to start learning about using the Arduinos built- in timer to create pauses and intervals.

Then you can start looking at “pin change interrupts”. It’s a bit of an advanced function, but I found it very rewarding to learn about the s.c interrupt functions on an early stage.

Basically it’s a way to have the Arduino keep track of any changes to a pin while it’s doing other stuff. Then, if the pin changes, it will halt everything and do some specified task before returning to the looping code. It’s called an ISR, Interrupt Service Routine.
I found Jeremy Bluhms video tutorials on YouTube very helpful and educational in this and other matters. Check them out.

Thank you for the advice :wink: