Alternative to delay function I am trying to make a workaround for the delay function. I am trying to use the function in the Analog Write Mega example, by replacing delay with the function i made. However, whenever i use my function instead of delay i get incorrect led behaviour. 

Here is the link to the example: 

https://www.arduino.cc/en/Tutorial/AnalogWriteMega

Here is my code:

int currmillis = 0; //used in my function to find the current millis()
int prevmillis = 0; //used to hold previous value of currmillis
int boolval = 0;    //used to control whether to write the brightness value to the led or not
int time = 0;     //used in the delay function, difference between currmillis and prevmillis

int timeloop(int); //the function i wrote, it is at the bottom of the code

void setup() {
  Serial.begin(9600);
  for ( int i = 2; i &lt;= 13; i++)
  {
        pinMode(i,OUTPUT); 
  }
}//Setting the pins to output and allowing serial communication.


void loop (){

  for ( int thisPin = 2; thisPin &lt;= 13; thisPin++ ) //to move from one led to the next
  { 

    for ( int brightness = 0 ; brightness &lt;= 255; brightness++) //change the brightness of the led
    {

      boolval = timeloop(2); //the delay function returns the time passed, if the time is greater than or equal to 2, the analogWrite will write the brightness to the led

      if (boolval &gt;= 2){ 
            analogWrite(thisPin, brightness);   
      }// if 2 ms pass, the led brightness will increase from 0 to 255 and then decrease in the following loop from 255 to 0, Once it reaches 0, the main loop moves to the next led.

    }

    for ( int brightness = 255 ; brightness &gt;= 0 ; brightness--)
    {
      boolval = timeloop(2);

      if (boolval &gt;= 2){ 
            analogWrite(thisPin, brightness);  
      }
    }
          timeloop(100); // a delay of 100 ms using the function
  }
}

int timeloop (int interval){ // the delay function

  do{
    prevmillis = currmillis; //hold previous value
    currmillis = millis(); //find current value 
    time = (currmillis-prevmillis); 
  }while(time &lt; interval); 

  return time;
}


Thank you
// You don't need to return anything since it's just a delay
// also I changed the parameters to long ints because millis()
// returns a long int
void timeLoop (long int startMillis, long int interval){ // the delay function

    // this loops until 2 milliseconds has passed since the function began
    while(millis() - startMillis &lt; interval){} 
}

// Your call for a 2 millisecond delay would be
timeLoop(millis(), 2);


Also the leds may be acting weird because this schematic is wrong. As you can see one of the led's anode isn't connected to ground. It's circled in red.


If you really want it to return something you could use this:

long int timeLoop (long int startMillis, long int interval){ // the delay function

    while(millis() - startMillis &lt; interval){} 
    return millis() - startMillis;
}


But it really isn't needed.