Why the delay command will create undesired output

I would like to use Arduino to act like a timer relay, which operate once i push a button and it will delay for some time to light on an led , and it would be turn off when release.

The thing goes wrong when i put delay function on the example: Button.
The output would delay for 2 sec, but once I release the button, it also takes 2 sec to switch off the led.

Can I know what causing it to run like that ?

const int buttonPin = 2;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
}

void loop() {
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);

  // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
  if (buttonState == HIGH) {
    // turn LED on:
    delay(2000);
    digitalWrite(ledPin, HIGH);
  } else {
    // turn LED off:
    digitalWrite(ledPin, LOW);
  }
}

Well yes. That's what that code would do. Loop is called repeatedly, so while holding down the button, it will keep going into that delay, and will still be in that delay when you release the button - you'll need to wait 0~2000ms (depending on where in that delay it was when you released the button) before it finishes the delay, loop gets called again, and can check the button state and act on it again.

delay() should only be used when you want the Arduino to stop doing ANYTHING during that time. That's not what you want. For more complex timing tasks, use millis(). A great deal has been written on it, as it is the most common programming question here. See: http://forum.arduino.cc/index.php?topic=503368.0

Please read the description of a forum section before you start a thread - this section specifically says it is only for tutorials, not for questions about your project! Also, use code tags - read this thread on using the forums: http://forum.arduino.cc/index.php?topic=148996.0

Try one more time to explain the way things should work, exactly, don’t miss out a step.

Do you now what the millis() function does?

.

The led would delay for some time to switch on once after i press the button, and it would directly turn off once i release the button.

Btw, I had just studied about the millis() function, from this link

Now i know that the concept of making it , it would be using the millis() function as a master clock, and my program would refer to it for the process.

The demo Several Things at a Time illustrates the use of millis() to manage timing without blocking. It may help with understanding the technique.

...R