I'm trying to simulate `setTimeout` with `spawn` but apparently it cannot work properly import threadpool from os import sleep type TimerObj[T] = object doit: bool time: int when T isnot void: arg: T exec: ExecProc[T] else: exec: ExecNoArg ExecNoArg = proc() Timer[T] = ref TimerObj[T] PTimer[T] = ptr TimerObj[T] proc runit(x: PTimer[void], duration: int) = sleep duration if x.doit: x.exec() proc setTimeout(exec: ExecNoArg, duration: int): Timer[void] = var temp: Timer[void] new temp temp.exec = exec temp.doit = true temp.time = duration spawn runit(temp[].addr, duration) result = temp proc cancelTimeout[T](timer: var Timer[T]) = timer.doit = false var timer = setTimeout( (proc() = echo "interweaving echo"), 300) cancelTimeout timer # should set the branch false and won't run the supply proc sleep 400 # if it works, it'll silently end
How to make it works correctly? Also, if any, please tell me a better approach for this. Thanks in advance.