Cant pause loop for specified amount of time

Hi, I want to make loop that will color circles but one circle at a time and every 2 seconds. So far Im using delay method with while loop but it makes my project freeze at the beginning and after some time it already shows all circles with changed color.

This is my draw method

void ofApp::draw(){
    int i = 0;
    while (i < vertices.size()) {
	    for (int j = 0; j < visitedToDraw.size(); j++) {
		    if (vertices[i].getId() == std::to_string(visitedToDraw[j])) {
			    vertices[i].drawBFS();
			    delay(1);
		    }
	    }
	    i++;
    }
}

Here is my delay method

void ofApp::delay(int number_of_seconds) {
	    // Converting time into milli_seconds 
    int milli_seconds = 1000 * number_of_seconds;

    // Stroing start time 
    clock_t start_time = clock();

    // looping till required time is not acheived 
    while (clock() < start_time + milli_seconds)
	    ;
}

Hey welcome to the forum :slight_smile:

It’s normally not a good idea to make a while loop that does nothing, as this will use all the CPU just to loop.

I normally do something like this:

// .h
float nextEventSeconds = 0;

// .cpp
void ofApp::draw(){
    float now = ofGetElapsedTimef();
    if(now > nextEventSeconds) {
        // do something here that should only happen
        // every 3 seconds
        nextEventSeconds = now + 3;
    }
}

So the idea is that your update() / draw() functions get called 60 times per second, but you just ignore them if it’s not yet time to do what you want to do. When the time comes, you do your thing, and then “reschedule” an event for later, in this case simply by having a variable that specifies when the thing should happen again.

If you you don’t want your background to be cleared automatically during those 3 seconds, you can call

ofSetBackgroundAuto(false);

inside setup(), so you will have to clear the background manually whenever you want. (In case you want to add a circle to the canvas every 3 seconds)

Thanks, this way works like a charm!