VocExile/Programming Topics/Time Delays

Programming Time Delays

In the course of program development, a programmer will find portions of a program, mainly involving input and output, need to be slowed down. If the program requires a single key press or a single mouse click to get you where you want to go, it is likely you will need a time delay to prevent multiple "hits" from occuring. It is also useful if you want your program to display various short messages just long enough that the user can read them.

The most obvious and easiest way to create a time delay is to create a "do" loop that will be executed for a set number of times. Unfortunately, PC's are getting faster and faster. If a program designed on an older machine is run on one of these new PC's, the time delays will become too short to be of any benefit to the user. If the program is run on an older, slower machine, the opposite problem occurs.

The moral to all of this is: Do not use timing loops to make time delays. Go to something that works the same speed in all computers: the computer's built in clock. Most programming languages should have provisions for accessing this piece of hardware.

The C code shown below demonstrates a time delay function. It can be called by the following program line:

delay(t)

where t is a floating point number that contains the time in seconds to pause the program. The value of t can be specified as a small fraction of a second or of many seconds.

#include stdio.h
#include time.h

void delay(float t)
{
....clock_t ticks;
....ticks = clock() + (clock_t) (t * (float) CLK_TCK);
....do { } while ( ticks > clock() );
}

Back to Programming Menu.

Back to Main Menu.


http://www.nfinity.com/~exile/delay.htm
Email: See bottom of Programming Menu
Date last updated: July 9, 1999