Keep "Opening" method code running with While True loop

I’m creating an onscreen digital clock which I want to refresh every 1 second. I’me using the Datetime method to get the current time (& date) and putting the result in a Label.

This works ok and displays the time when I run the code. But I can’t get the code to refresh.

Coming most recently from Python, I think a While True … Wend loop would do this, but I can’t get it to work. I’ve tried this loop in the Opening method of the time display label, but it never displays the clock and hangs.

Current code:

  'While True
  Var d As DateTime = DateTime.Now
  Var Hrint as integer = d.Hour
  Var minint As integer = d.minute
  Var secint As integer = d.second
  Var Hr as String
  Var min as String
  Var sec as String
  if Hrint < 10 then  
    Hr = "0" + str(Hrint)
    Hr = str(Hrint)
  end if
  if minint < 10 then  
    min = "0" + str(minint)
    min = str(minint)
  end if
  if secint < 10 then  
    sec = "0" + str(secint)
    sec = str(secint)
  end if
  TimeDisplay.Text = str(Hr) + ":" + str(Min) + ":" + str(sec) 
  ' Wend

Sorry - I can’t find how to format the code!

Can anyone please help & point me in the right direction?

Use a Timer instead of the loop.


Unfortunately, that’s the worst way to do it in Xojo. The While loop blocks the UI update. Use a Timer like Greg suggested.

API 1 old Examble clock

Draw your own clock

Thank you all for these replies - most helpful, and I think I will be able to proceed now.

Tim - I knew that the while loop I had was blocking the rest of the code - what I didn’t know was what to do about it! But the replies have put me on the right course

Happy Christmas to all

str have optional format argument, you could remove this if then and variables too.

Thanks MarcusR for that tip - very useful. I didn’t know that format argument was available, but hadn’t really looked - at this stage I’ve just been trying to get the code to work and the other replies have helped with that.

1 Like