'How to delay in c++?

I am working on a rehabilitation application that relies on four ARuco markers,i need to draw on the four markers in the exercise sequence i.e. the object appears on the first marker, when the patient's hand reaches the object, it moves to the next marker, etc... . I could draw on only the first marker by selecting its marker id, now i need to make a delay to draw on the next marker, here is the code:

std::vector<int> ids;
    std::vector<std::vector<cv::Point2f> > corners;
    cv::aruco::detectMarkers(image, marker_dict, corners, ids);

    // Draw markers using opencv tool
    cv::aruco::drawDetectedMarkers(mid, corners, ids);

    // Draw markers custom
    for (size_t i = 0; i < corners.size(); ++i)
    {

        // Convert to integer ponits
        int num = static_cast<int>(corners[i].size());
        std::vector<cv::Point> points;
        for (size_t j = 0; j < corners[i].size(); ++j)
            points.push_back(cv::Point(static_cast<int>(corners[i][j].x), static_cast<int>(corners[i][j].y)));
        const cv::Point* pts = &(points[0]);


        // Draw


        if (ids.at(i) == 45) {
            cv::fillPoly(right, &pts, &num, 1, cv::Scalar(255, 0, 0));
        }
        


Solution 1:[1]

Use the std::chrono library to measure time that has passed, when your desired delay has passed, execute the code you want at that time.

Here is a simple example using a while loop which checks if 100 milliseconds have passed

#include <windows.h>
#include <iostream>
#include <chrono>

int main()
{

    using Clock = std::chrono::steady_clock;
    std::chrono::time_point<std::chrono::steady_clock> start, now;
    std::chrono::milliseconds duration;

    start = Clock::now();

    while (true)
    {

        now = Clock::now();
        duration = std::chrono::duration_cast<std::chrono::milliseconds>(now - start);

        if (duration.count() >= 100)
        {
            //do stuff every 100 milliseconds
            start = Clock::now();
        }
    }

    return 0;
}

No sleep necessary either.

Solution 2:[2]

You can use the headers chromo and thread. After the function, you can put the sleep(); anywhere with the amount of seconds in the brackets. You can use decimals and whole numbers.

#include <iostream>
#include <chromo>
#include <thread>
void sleep(float seconds){
clock_t startClock = clock();
float secondsAhead = seconds * CLOCKS_PER_SEC;
// do nothing until the elapsed time has passed.
while(clock() < startClock+secondsAhead);
return;
}
int main(){
sleep(2); 
cout << "Hello " << endl;
sleep(2.5);
cout << "World!" << endl;

return 0;   
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 GuidedHacking
Solution 2 Keenan Ravi