What is wrong with this code? I am trying to write a sub that allows me to pause my code for the specified period of time. But when I run this it just sits in an infinite loop. I was expecting d to be static, but it keeps incrementing it’s value to ‘Now’ each time it is read AFAICT
Sub Sleep(DurationInSeconds as Integer)
Var di as New DateInterval
Var d as DateTime = DateTime.Now
Do Until di.Seconds > d.SecondsFrom1970 + DurationInSeconds
di.Seconds = d.SecondsFrom1970
You need to increment di.Seconds to be able to be more than (d.SecondsFrom1970 + DurationInSeconds), no?
Thread.Sleep will do this within a thread. Doing something like this outside of a thread will lock up the whole program.
You can use a Timer to do this as well.
It’s a bad idea: not only will it lock up the program, the app will use 100% CPU, and on macOS you will get the beachball, and on Windows you’ll get the “This app has stopped responding” dialog.
The answer is to think about Event-driven programming, where you use Timers, Threads, etc. to accomplish the goal.
Can you say more about why you would want this Sleep() function in the first place?
The reason behind my thinking was more simply a case of being a noob with Xojo at the moment. So all this is learning for me.
On a related question, can you see why my Sub was not calculating the difference in seconds correctly? The Do Until condition was never met.
You’re assuming that
d.SecondsFrom1970 updates as time passes. It doesn’t.
hmmm. why not? each second passed is 1 second more since 1970, or am I not understanding something?
Var d as DateTime = DateTime.Now just gives you a snapshot at the instant that statement is executed.
This will work but as a Tim pointed out, it will lock up the whole app for the duration.
OK, thanks. So I was totally overthinking it.
I ditched it for Tim’s suggestion anyway!