QB / QB64 Discussion Forum      Other Subforums, Links and Downloads
 

 Return to Index  

How to use SLEEP correctly

December 5 2008 at 11:38 AM
Clippy  (Login burger2227)
R

 

Before I begin, I usually go to bed at 4AM and wake up at Noon! So don't follow my SLEEPING habits if you have a job! OK Pete, your turn....

SLEEP allows you to stop a program for an integer number of seconds. Such as : SLEEP 5 'waits 5 seconds

SLEEP without a time just waits until a key is pressed, but ANY SLEEP statement can be canceled by a keypress. What you may not realize is that the keypress stays in the keyboard buffer. Thus if a key is pressed, that key shows up in an INPUT or INKEY$ loop. Try this example:

PRINT "Press any Key"
SLEEP

INPUT "Name: ", user$

The first letter is the key you pressed in SLEEP. Same with an INKEY$ loop! To avoid this, you need to clear the key buffer as shown:

DO: LOOP UNTIL INKEY$ = ""

Then you can use INPUT, LINE INPUT, or an INKEY$ loop.

SLEEP also allows the background programs, such as Windows, to have the CPU time. So you can use SLEEP in a simple INKEY$ wait loop allowing background programs some room:

DO: SLEEP: LOOP UNTIL INKEY$ <> ""

When no key is pressed, SLEEP stops the loop. When a key is pressed it exits the loop and clears the keypress.

For Delay loops that are not affected by keypresses you can use a TIMER Delay loop. Also clear the keypress buffer in the Delay or after it if necessary. TIMER Delays can be down to about .05 seconds. TIMER loops, like normal loops, allow no free CPU time and can cause other programs to interrupt your program.

Ted




    
This message has been edited by burger2227 on Dec 5, 2008 5:40 PM


 
 Respond to this message   
 Copyright © 1999-2014 Network54. All rights reserved.   Terms of Use   Privacy Statement  

Newbies usually go to www.qbasic.com and click on The QBasic Forum
Forum regulars have their own ways, which include The QBasic Community Forums