Search Projects

Saturday, August 4, 2012

How to display Timer in OpenGL Projects

This tutorial will demonstrate how to have timer in the project of computer graphics using OpenGL. Follow the simple steps and get you timer in the projects.

To have timer in the program, OpenGL had provide a library function. This library function is "glutTimerFunc" which need to be called to have the timer displayed. So to have this function work we will define and declare a function called myTimer, whose code is like-

void myTimer(int value) {

g_counter = value + 1;
else if(j==1)
g_counter = value + 0;
g_counter = 0;
glutTimerFunc(GAP, myTimer, g_counter);

You must have g_counter variable declared before you define this function like this. The g_counter, must be declared as a static variable. So you use it like static int g_counter = 0; where it has been initialized to 0 at first to start from 0, if you wish you can set the other time. Also have another variable J, this too must be static go as static int j=0; also initialized to 0.
There are three if else statements, first it check whether the timer is at initial position if it is, then value of   g_counter would be incremented by 1. Further second if, check that timer has been paused as value of j changes to 1, then no increment in g_counter  and last one rest the g_counter value to 0.

glutTimerFunc take three parameter of which first is the value in millisecond here it determines to have per second value. Second his the function called to process the timer, third and the last the value that determine the timer's value.

Now we will desgin a keyboard function that will cause the timer to start, stop and reset. The code for that is below -

void myKey(unsigned char k, int x, int y)
switch (k) {
case 's': if(j==0)j=1; else j=0; break;
case 'r': j=2; break;
case 'q':

From the code most of the things is clear. As User press the 's' key the timer will stop first and if 's' was pressed again, the timer start from where it stopped. The logic is simple, first time when key 's' is pressed the value of j changes to 1 and it changes to 0 when press again, the  value of j is checked in myTimer function and g_counter is incremented accordingly. The  'r' is used to reset the value of the timer to 0, while 'q' will quit the program.

Download the simple timer program from here.


  1. please send the code for this

  2. you posted 10 comment by asking the project code but all post have the download link can't u get it from there?