import os
while true:
myProc()
sleep(2000)
setTimeout implementation is left as an exercise for the reader.
You can use the standard libraries asyncdispatch which provides you with sleepAsync().
import std/asyncdispatch
proc runLater() {.async.} =
while true:
await sleepAsync(2000)
echo "sleep done"
asyncCheck runLater()
echo "waiting"
runForever()
proc sleepAsync*(ms: int | float): owned(Future[void]) =
## Suspends the execution of the current async procedure for the next
## `ms` milliseconds.
var retFuture = newFuture[void]("sleepAsync")
let p = getGlobalDispatcher()
when ms is int:
p.timers.push((getMonoTime() + initDuration(milliseconds = ms), retFuture))
elif ms is float:
let ns = (ms * 1_000_000).int64
p.timers.push((getMonoTime() + initDuration(nanoseconds = ns), retFuture))
return retFuture
No, it's not.
So I'm trying to writing a setInterval/clearInterval using function closure, but it clearly doesn't work and I'cant figure out how can I do with it:
import std/asyncdispatch
import sugar
proc runInterval(cb: proc, intv: int): Future[proc()] {.async.} =
var stop_run = false
while not(stop_run):
await sleepAsync(intv)
cb()
proc clearInterval() =
stop_run = true
return clearInterval
let clearInterval = runInterval(()=>echo "hahah", 1000) # the clearInterval can't be called
runForever()