Use a photoresistor to stop program when it reads a low value

Hello programmers,

I made a program to sweep a dc motor back and forth when i press the start button.
I also have a stop button which stops teh program. Yet it only stops the program when i hold this button till the if-loop ends. I would like it to stop instantly.

This is the current code:

#define CW 7 //CW is defined as pin #7//

#define CCW 8 //CCW is defined as pin #8//
const int buttonPin = 2; 
const int buttonPin1 = 12; 
int buttonState = 0;  
int buttonState1 = 0;  
int run;

void setup() { //Setup runs once//
  Serial.begin(9600);
 run = 0; //starts stopped
pinMode(CW, OUTPUT); //Set CW as an output//

pinMode(CCW, OUTPUT); //Set CCW as an output//
pinMode(buttonPin, INPUT);
pinMode(buttonPin1, INPUT);

} 

void loop() { //Loop runs forever//
   
buttonState = digitalRead(buttonPin);  
  
if (buttonState == HIGH) { 
    if(run == 0)
     {
         run = 255;
     }
     else
     {
         run = 0;
     }

  }

  if(run > 0)
  {
digitalWrite(CW,HIGH); //Motor runs clockwise//

delay(5000); //for 1 second//

digitalWrite(CW, LOW); //Motor stops//



digitalWrite(CCW, HIGH);//Motor runs counter-clockwise//

delay(5000); //For 1 second//

digitalWrite(CCW, LOW); //Motor stops//

    
     //code you only run if button was pressed, stops running when button pressed again, so forth...
  }
 buttonState1 = digitalRead(buttonPin1);
  if (buttonState1 == HIGH) { 
    run = 0;
  }
  }  


//end of code//

With this i want to install 1 photoresistor. it will read the light level in the setup of the program. lets call this startvalue". i want the same resistor to read the light level while the program runs. If the light level is below the startvalue i want the program to stop. I now use this code for the resistor:

int value;
const byte resistorpin = A1;
int lightCal;

Void setup(){
lightCal = analogRead(resistorpin);
}
Void loop(){
if (value < lightCal - 100){  
[the code....]
}

I cant get it to work. Sometimes it does stop but only after the loop ends. Does anyone know how i can fix this?

So i need a button to be pressed once and stop my program instantly. And i need a program that uses a resistor to stop the program instantly but for as long as the light level is below the value read in the setup.

it only stops the program when i hold this button till the if-loop ends. I would like it to stop instantly.

First a minor correction. There is no such thing as an if-loop. There are program statements that execute when the if condition is true, but no loop

The problem is the delay()s in the block of code dependent on the if. They prevent anything from happening whilst the delay() is in progress, including reading an input. How to get round this common problem ?

Have a look at Using millis() for timing. A beginners guide, Several things at the same time and look at the BlinkWithoutDelay example in the IDE.