Enchanter
Enchanter

Reputation: 117

Wish To Execute A Function Periodically But Continue With The Rest Of Program Loop

Currently my program consists of a main loop which executes whilst a window is open. Inside the loop there is a function which must execute periodically (say every second or so), BUT the rest of the main loop has to continue executing and the loop to repeat without the periodic function being executed until the time is up. My question is - how can you execute the function periodically in the main loop without halting program execution altogether? Here is the code:

//Prototypes
void functionToBeExecutedPeriodically();
void someFunc1();
void someFunc2();

int main()
{ 
    while (window.isOpen())
    {                                             
        functionToBeExecutedPeriodically();

        //This part of the loop must continue executing whilst the above 
        //idles for a limited period of time
        someFunc1();
        someFunc2();
        window.display();
    }
}

Upvotes: 0

Views: 624

Answers (1)

A. D.
A. D.

Reputation: 758

With a timer for example:

int main() { 
  sf::Clock timer;
  while (window.isOpen()) {
    if (timer.getElapsedTime() >= sf::seconds(1.0f)) {
      functionToBeExecutedPeriodically();
      timer.restart();
    }
    someFunc1();
    someFunc2();
    window.display();
  }                          
}

That would execute the function every second.

Upvotes: 1

Related Questions