Search code examples
loopsdelaysmalltalkpharo

Smalltalk - Print something for each 2 seconds


I'm coding in Smalltalk using Pharo. My code:

|i delay|
i := 0.
[i < 5] whileTrue: [
    [
        delay := Delay forSeconds: 2.
        delay wait.
        Transcript show: '2 seconds are up'.
        Transcript cr.
    ] fork.
    i := i + 1.
]

It prints all the "2 seconds are up" at once, and not for each 2 seconds:

2 seconds are up
2 seconds are up
2 seconds are up
2 seconds are up
2 seconds are up

Please, can anyone tell me how to print something for each 2 seconds in Smalltalk?


Solution

  • You forked all 5 processes at once so that all 5 delays ends at the same time. To print every 2 seconds from the background, rather fork a whole loop in a separate process:

    |i delay|
    [   
        i := 0.
        [i < 5] whileTrue: [
            delay := Delay forSeconds: 2.
            delay wait.
            Transcript show: '2 seconds are up'.
            Transcript cr.
            i := i + 1]
    ] fork