Have you ever wanted to create a C program that waits for a certain amount of time? You can customize the way to give the time "fly by", for example: when showing a pop-up page (notification or hint) for the game. … OK, here are some ways to create a "stand still" program, read on …
Steps

Step 1. Let your processor run for a while without causing an observable event

Step 2. Do not perform any other operations during this delay to create a simple time delay
Method 1 of 2: For-loop technique

Step 1. Use a typical "for" loop followed by an empty statement to implement a delay

Step 2. Write as follows, for example
- for (i = 1; i <100; i ++);
- The operator following the ";" forces the computer to loop 100 times without a noticeable event. It only creates a time delay.
Method 2 of 2: The "sleep ()" technique

Step 1. Use sleep ()
The function is called sleep (int ms), declared in, which makes the program wait for a specified amount of time in milliseconds.

Step 2. Include the following line in your program before int main ()
#include

Step 3. Paste where needed to make your program delay
- sleep (1000);
- Change "1000" to the number of milliseconds you want to wait (for example, if you want to make a 2 second delay, replace it with "2000".
- Tip: On some systems, the value may be specified in seconds instead of milliseconds. Therefore, sometimes 1000 is not 1 second, but actually 1000 seconds.
Sample code
A program that waits for a certain number of seconds:
#include #include int main () {int del; // The delay period printf ("Enter the delay time (in seconds):"); scanf ("% i",? del); del * = 1000; // Multiply it by 1000 to convert to milliseconds Delay (del); // Delay. printf ("Done."); return 0; }
A program that counts down from 10 to 0:
#include #include int main () {int i; for (i = 10; i> = 0; i--) {printf ("% i \ n", i); // Write the current 'countdown' number Delay (1000); // Wait a second} return 0; }
Advice
- A millisecond is 1/1000 of a second.
- The above algorithm can be implemented using any looping structure followed by the null operator - "; as using while or do-while loops.
Warnings
- This method is generally useless for anything other than a trivial program. In general, use timers or an event-driven approach to accomplish this. Otherwise, the program will become unresponsive during the delay time and this is not always a good thing. Also, choosing N in a loop, if it depends on the execution of commands, can have unexpected results. Apparently the original author has never heard of an optimizing compiler … it can optimize the entire loop if it doesn't actually do anything!
- Note that when using the "for-loop" method, it may take a very large interval for i, since an empty statement is very fast. Such large numbers may not fit into an integer type.
- If you use a for-loop, the compiler can optimize the code, and since the loop does nothing, remove it. This does not happen when using Delay ().