Best way to wait/sleep/delay?


Hi Everyone,

This is my first post here! I just started using JUCE and I am liking it so far. I used to be a full-time Tracktion user way before I started programming, so it is cool to see under the hood.

I am working on an audio processing program that I eventually want to make into a VST. For now, I am just trying to do extremely simple audio stuff. I have figured out how to listen to the default audio input and detect peaks over a user-set threshold. I have an AudioIODeviceCallback that also multiple inherits from ActionBroadcaster; when it finds a peak it broadcasts an action back to the main component.

I would like to display a big red square during a peak, but revert to a different color when the audio isn’t peaking. But the red square needs to show for long enough to see it, so I want it to delay for a little bit after the peaking is over.

What is the best way to make my code display the red for a duration, say 100ms, before going back to blank? Naturally, I don’t want to tie the CPU up in the action listening method for that whole duration.



You can use



waiting in callback procedure is the wrong approach (and it will block the message thread, nothing will be repainted, your app just freeze) , use the Timer class, a counter which will be decremented in the timerCallback and then change the colour when the time is over (or use some other mechanism)


For anyone looking for quick, general answer for how to wait/sleep in Juce, this command will wait for one second

Time::waitForMillisecondCounter(Time::getMillisecondCounter() + 1000);


A quick answer 5 years later? :smiley:



Yes. The reason is, when I type “juce sleep” on Google, this thread is still the first one, so I think people might find it usefull :slight_smile: .


…but it is still the wrong answer. Please read @chkn’s answer above. In 99% the answer is not sleep!

// in audio thread save the time, when the over occured:
Atomic<int64> over;

if (value > 1.0)
    over = Time::currentTimeMillis(); 

// in your editor's paint
if (processor.over + timeout > Time::currentTimeMillis())
    // draw your over
    // draw normal

You always want to return as quick as possible, so the event loop can do it’s work and call other events.

Hope that helps


Thanks for you effort, but I’m not even trying to answer the OP. Reason explained above.


Ok, to all people coming from google:
please avoid calling sleep/wait or delay method from Thread, if you don’t know how multi threading works (*).
Not relating to your answer :wink:

*) if you didn’t write/instanciate the thread. Don’t sleep in the message thread, don’t sleep in the audio thread. And especially if you don’t know, what’s that about: calling sleep is not the solution you are looking for.