Home c++ How to create a delay in your code

How to create a delay in your code

Author

Date

Category

I wrote a snake, but it moves very quickly. To fix, you just need to add a delay at the end of the while loop, for example, half a second, how to do it?


Answer 1, authority 100%

You have several options for solving this problem:

Option 1:

# include & lt; thread & gt;
#include & lt; chrono & gt;
...
std :: this_thread :: sleep_for (std :: chrono :: nanoseconds (500000000));

Option 2:

# include & lt; unistd.h & gt; // for Unix systems
...
sleep (500);

Option 3:

# include & lt; windows.h & gt; // for Win32 systems
...
Sleep (500);

Option 4:

# include & lt; dos.h & gt; // for Win32 systems
...
delay (500);

But of course, these options are not the best way to solve this problem. In particular, I would make a timer (clock generator) for the snake, which would change the position of the snake on the field for each tick, and also generate new food for the snake, for example, and much more … You can read more about this here .


Answer 2, authority 100%

sleep to help. But depending on the axis / compiler, there may be different solutions, but with the new standard you can use sleep_for

A half second delay will look like this

std :: this_thread :: sleep_for (500ms);

Answer 3, authority 50%

Use Sleep in a motion loop (number of milliseconds)

(Below is an example code that you can run from yourself to see how everything works)

# include & lt; iostream & gt;
#include & lt; cstdlib & gt;
short a = 0;
int main () {
  while (a & lt; 10) {
  a ++;
  std :: cout & lt; & lt; a & lt; & lt; std :: endl;
  Sleep (1000);
  system ("cls");
  }
}

Answer 4

well there is # include & lt; windows.h & gt;

and there is a function sleep (number of milliseconds) it stops the program for so many milliseconds (1000 milliseconds = 1 second)

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions