Home
Free Midlets
Help

SLEEP

Syntax: SLEEP constant | variable | expression

The SLEEP command is used to introduce small delays in your program. The argument is an integer which specifies the number of milliseconds the program should wait for. If the argument is zero, or negative, then the SLEEP command causes the program to briefly yield the processor to allow other tasks to run. If there are no other tasks waiting then the BASIC program resumes immediately.

Tip: Always use "SLEEP 0" or "SLEEP 1" in the main loop of a game – it will give the screen chance to update. Wherever possible use "SLEEP 1" in the loop since it can have a dramatic reduction on the amount of CPU processing power used – which could improve battery life.

Example 1 – No Sleep

10 IF FIRE(0)<>0 THEN GOTO 30
20 GOTO 10
30 END

The effect of not using the "SLEEP" command at all is that the program will repeatedly check for the fire key being pressed. This is may be done millions of times per seconds (depending on the phone). There are several effects:- 1) There is less processor time to other important tasks such as updating the screen. 2) The battery life may be reduced because the CPU is being used all the time.

Example 2 – SLEEP 0

10 IF FIRE(0)<>0 THEN GOTO 40
20 SLEEP 0
30 GOTO 10
40 END

The effect of using "SLEEP 0" is similar to Example 1. The main difference is that other tasks, such as screen updates, are given chance to run when the SLEEP is executed. If there are no other tasks waiting then the BASIC program resumes immediately. As in case 1, the battery life may be reduced because the CPU is being used all the time.

Example 3 – SLEEP 1

10 IF FIRE(0)<>0 THEN GOTO 40
20 SLEEP 1
30 GOTO 10
40 END

Using "SLEEP 1" is much more friendly to the phone. It allows other tasks to run more readily and greatly reduces the amount of CPU processing power consumed. For example, lets say that your phone processor runs at 10MHz – 10 million instructions a second. It will only take the processor a small number of instructions to work out if the FIRE button has pressed - lets say its 100 instructions for sake of an example. This would result in the loop being executed 100000 times a second. Is this necessary? Do you need to detect the FIRE button being pressed within 1/100000 second? Probably not! "SLEEP 1" puts the program to SLEEP for 1/1000 second before it checks again. The result is that the program will check the FIRE button 1000 times a second using 100 instructions each time. The total number of instructions executed would be 100*1000 = 100000 which is 1% of the available processing time. The remaining 99% of the processor time is now idle which may reduce power consumption as well as giving the screen more chance to update.