How to time IO output

Hi crew, I’m glad to be joining the community (a bit more actively, anyway) as a novice. If this is not the right place to direct rookie questions, please advise me where to direct them.

I have been trying to write a simple program which performs IO actions at specified time delays - e.g write a sentence, letter by letter, with one second between each letter. I have scrolled and searched the Googles for an hour and am surprised I haven’t found a solution to something so fundamental. I have found under Data.Time.Clock a getCurrentTime variable (:: IO UTCTime) and could use this to delay in a function such as

wait t = do
            x <- getCurrentTime
            if (x < t) then  
                            wait t 
            else return 

(I am sure this has syntactical errors). If wait t was used in a do block it should repeatedly check the current time, and only move on when the time t is reached. But this seems like it would be an unnecessary burden on the processor, constantly checking. Is there a more elegant way?

1 Like

You’re looking for threadDelay from the Control.Concurrent module.

3 Likes

Minor threadDelay advice: the NumDecimals extension makes the function easier to use, as it lets you write threadDelay 1e6 instead of threadDelay 1000000.

3 Likes

I recommend using the getTime function from the clock package:

The package also has functions to calculate the difference between two measurements.

1 Like