Casimir Kash
Casimir Kash

Reputation: 42

How to add a delay to code in C++.

I want to add a delay so that one line will run and then after a short delay the second one will run. I'm fairly new to C++ so I'm not sure how I would do this whatsoever. So ideally, in the code below it would print "Loading..." and wait at least 1-2 seconds and then print "Loading..." again. Currently it prints both instantaneously instead of waiting.

cout << "Loading..." << endl;
// The delay would be between these two lines. 
cout << "Loading..." << endl; 

Upvotes: 1

Views: 16667

Answers (4)

2785528
2785528

Reputation: 5566

to simulate a 'work-in-progress report', you might consider:

// start thread to do some work
m_thread = std::thread( work, std::ref(*this)); 

// work-in-progress report
std::cout << "\n\n  ... " << std::flush;
for (int i=0; i<10; ++i)  // for 10 seconds
{
   std::this_thread::sleep_for(1s); // 
   std::cout << (9-i) << '_' << std::flush; // count-down
}

m_work = false; // command thread to end
m_thread.join(); // wait for it to end

With output:

... 9_8_7_6_5_4_3_2_1_0_

work abandoned after 10,175,240 us

Overview: The method 'work' did not 'finish', but received the command to abandon operation and exit at timeout. (a successful test)

The code uses chrono and chrono_literals.

Upvotes: 1

Serge
Serge

Reputation: 12354

in c++ 11 you can use this thread and crono to do it:

#include <chrono>
#include <thread>
...
using namespace std::chrono_literals;
...
std::this_thread::sleep_for(2s);

Upvotes: 6

Piyush Sonani
Piyush Sonani

Reputation: 32

In windons OS

#include <windows.h>
Sleep( sometime_in_millisecs );   // note uppercase S

In Unix base OS

#include <unistd.h>
unsigned int sleep(unsigned int seconds);

#include <unistd.h>
int usleep(useconds_t usec); // Note usleep - suspend execution for microsecond intervals

Upvotes: 0

Saustin
Saustin

Reputation: 1147

You want the sleep(unsigned int seconds) function from unistd.h. Call this function between the cout statements.

Upvotes: -1

Related Questions