• 12
• 12
• 9
• 10
• 13

# Very weird timer issue

This topic is 2177 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## [font=arial,helvetica,sans-serif][color=#000000]Anybody have any ideas on what I'm missing?[/font]

##### Share on other sites
what makes you think that the for loop increments seconds if the Delay isn't included?

##### Share on other sites
The following works fine on my system:

#include <ctime> #include <iostream> using namespace std; void Delay (int seconds) { clock_t t = clock() + (seconds * CLOCKS_PER_SEC); while (clock() < t) ; // this semi-colon has the exact same effect as { } } void StartTimer(int seconds) { for (int i = 0; i < seconds; i++) { int remaining = seconds - i; if (remaining == 60) cout << "\n60 seconds remaining"; else if (remaining == 45) cout << "\n45 seconds remaining"; else if (remaining == 30) cout << "\n30 seconds remaining"; else if (remaining == 20) cout << "\n20 seconds remaining"; else if (remaining == 10) cout << "\n10 seconds remaining"; // cout << remaining << "\n"; //for some reason nothing prints at the // right time unless I include this line. Delay(1); } } void main (void) { StartTimer(60); }

However, may I recommend a switch statement instead:

void StartTimer(int seconds) { for (int i = 0; i < seconds; i++) { switch(seconds-i) { case(60): cout << "\n60 seconds remaining";break; case(45): cout << "\n45 seconds remaining";break; case(30): cout << "\n30 seconds remaining";break; case(20): cout << "\n20 seconds remaining";break; case(10): cout << "\n10 seconds remaining";break; } Delay(1); } }

... or even more compact:

void StartTimer(int seconds) { for (int i = 0; i < seconds; i++) { switch(seconds-i) { case(60): case(45): case(30): case(20): case(10): cout << "\n" << int(seconds-i) << " seconds remaining"; } Delay(1); } }

##### Share on other sites
Thanks for the help. Sorry it took so long to get back (school is super busy this quarter).

@ Telastyn: I'm calling Delay(int seconds) in the for loop, so the loop should run once every second, so I'm not really sure what you mean.

@ Dragonion: I wonder why it runs fine on yours? I cleared all my other code in main() and just called StartTimer(). When the 60 second mark comes around it just prints a blank new line, then prints 60 at the 45 second mark, 45 at the 30, and so on. Even if I call StartTimer(35) it just prints a newline at the first "mark" and is always behind in the display. The counting is just fine, but it prints late (10 at 0 is kind of misleading to the player). Any thoughts on what might be causing this?

By the way, thanks for showing the shorter switch statement. I've used them before but never that concisely