Infinite loop

 

Hi!

Consider this code: 

int a = 1;

void start(){
    
   while (a == 1) {
       p("In the while loop");
       GoToSleep();
         
   }
}

//*****************************************
void GoToSleep(){
   p("Sleeping");
   Sleep(10000);
   p("Sleep DONE...");
}

//*****************************************
void p(string Txt){
   Print(Txt);
}

If I use this code on a chart it works fine until I remove it!

When I remove it from the chart, then it start to go in an infinite loop, printing "In the while loop", Sleeping" and "Sleep DONE..." like crazy, not respecting the Sleep(10000) line.

I tried this as an EA and as a Script. They both behave the same way.

Any idea why?

The program should just die when I unload it...

Thanks!!

 
   while (a == 1 && !IsStopped()) {
       p("In the while loop");
       GoToSleep();
   }

Your function is aborting the Sleep due to the terminal trying to unload the program, but the loop never quits so the show goes on and on. Check it like this.

 

For the execution you aim to accomplish its better to utilize TimerEvents . 

https://www.mql5.com/en/docs/eventfunctions/eventsettimer

https://www.mql5.com/en/docs/event_handlers/ontimer

Documentation on MQL5: Working with Events / EventSetTimer
Documentation on MQL5: Working with Events / EventSetTimer
  • www.mql5.com
The function indicates to the client terminal, that for this indicator or Expert Advisor, events from the timer must be generated with the specified periodicity. Normally, this function must be called from the OnInit() function or from a class constructor. In order to handle events coming from the timer, the Expert Advisor must have the...
 
Thanks guys!!! Really appreciated!!
Reason: