How to call multiple delayed functions using a single millis() I am working in a project where I need to call more than 1 functions actually 4 functions using a single millis()
Here is the code below.
 unsigned long then = 0;

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

     if(now-then &gt;=0){
    
    
         Serial.println(&quot;Function 1 called&quot;);
    
    
     }else if(now-then&gt;=2000){
      
      
         Serial.println(&quot;Function 2 called&quot;);
    
    
     }else if(now-then&gt;=4000){
     
     
         Serial.println(&quot;Function 3 called&quot;);
     
     
     }else if(now-then&gt;=6000){
        
        Serial.println(&quot;Function 4 called&quot;);
         
         Serial.println(&quot;The end&quot;);
      
         then = now;
     }
 }

All the functions above gets run successfully but not in a proper sequence.
The running sequence of the functions seem to be very improper and random.
The 'function 1' gets executed in a proper sequence and timing but rest of the others are making a messy output.
How can I fix it please?
Thanks.
The current structure with multiple if statements and on timestamp variable does only work, if you also check for millis()-then being smaller than the next interval. Otherwise the first if statement will always be executed.
I think it gets easier, when you use only one if statement, but put the intervals in an array. In that if statement you can either use a switch statement to execute the code for the corresponding interval, or use a function pointer. Somewhat like this (untested):
unsigned long then = 0;
unsigned long intervals[4] = {0, 2000, 4000, 6000};
int current_interval_index = 0;

...

void loop(){
    unsigned long now = millis();
    if(now-then &gt;= intervals[current_interval_index]){
        switch(current_interval_index){
            case 0:
                Serial.println(&quot;Function 1&quot;);
                break;
            case 1:
                Serial.println(&quot;Function 2&quot;);
                break;
            case 2:
                Serial.println(&quot;Function 3&quot;);
                break;
            case 3:
                Serial.println(&quot;Function 4&quot;);
                break;
        }
    then = now;
    current_interval_index = (current_interval_index + 1) % 4; // increment index and wrap it back to zero, if it goes to 4 
    }
}

That way you can easily extent for more functions and the intervals are conveniently managed in an array. Note, that the intervals add up here. So function 4 executes after 2s+3s+6s = 11s.