Skip to content
Sign upLog in
← Back to Community

How do I delay code in swift?

Profile icon
JDOG787Hacker

I can't figure out how to delay code in swift. I'm modifying one of my repls and I want some of my code be delayed but I can't figure out how to do it. pls help
Also this is the repl I'm working on. Its not much but its my first repl.
my repl
Thanks

Voters
Profile icon
sapw3166
Profile icon
Coder100
Profile icon
ArtemPionov
Profile icon
JDOG787
Comments
hotnewtop
Profile icon
Krazy0range

This works for me!

usleep(1000000)

usleep takes a time in milliseconds, so the code above would wait for 1 second, so this is what I do:

func Wait(_ time: UInt32) { usleep(time * 1000000) }

That function above takes one argument, time, which is how many seconds to wait. This should work, because I use it myself. Hope this helps!

Profile icon
JDOG787

@CodeABC123
These don't work for some reason. The first I knew about but it does work. second doesn't work I think because it use objective c. All of them give me an error.

Profile icon
[deleted]

This might help.

Profile icon
ArtemPionov

'''
do {
sleep(4)
}
'''
I did some research, maybe this would help.

Profile icon
JDOG787

@ArtemPionov
I try this out and it gave an error. When I work in Xcode

'''
DispatchQueue.main.asyncAfter(deadline: .now() + 42.0) {
// do stuff 42 seconds later
}
'''
worked but it doesn't in repl.it.

Profile icon
ArtemPionov

@JDOG787
Oh ok, sorry man that's not my programming language all I did was try to help. :D

Profile icon
JDOG787

Thanks for trying

@ArtemPionov
also do you like my repl?

Profile icon
ArtemPionov

@JDOG787
I'm not into Swift but I like it!

Profile icon
JDOG787

@ArtemPionov
Thanks