Delayed execution of some code
Last updated at 2:24 pm UTC on 16 April 2008
Delays are handled by class Delay.
The class messages forSeconds: and forMilliseconds: are used to create and set the delay interval. The instance method wait on the resulting instance of Delay delays execution for the approximate amount of time set by one of the mentioned class messages.
Examples (doIt in a Workspace, have Transcript open):
Transcript clear; show: 'Before delay: ', Time now printString.
(Delay forSeconds: 2) wait.
Transcript cr; show: 'After delay: ', Time now printString.
3 timesRepeat: [ Transcript show: Time now printString; cr.
(Delay forMilliseconds: 2000) wait ]
[ 1 to: 5 do: [ :i | Transcript show: i printString, ' > ', Time now printString; cr.
(Delay forSeconds: 2) wait ] ] fork
"Example 4 (after an example in Alec Sharp: Smalltalk by Example)"
Transcript clear; show: 'Start'; cr.
process := [ [ Transcript show: 'Hi there!'; cr.
(Delay forMilliseconds: 500) wait ] repeat ] fork.
(Delay forSeconds: 3) wait.
Transcript show: 'Done'.
Note that in Examples 1 and 2 the delay is executed as part of the user interface process, so it is not possible to activate the Transcript to see what's going on while the delay is running (in case your Workspace is overlapping the Transcript). In Example 3 and 4 a separate process is started with the fork message send to the block which is to be executed. In Example 4 the separately executing process (an endless loop) is terminated after another delay (try different lengths) by the message terminate.