在 nim 中实现 setInterval/clearInterval

implementing setInterval/clearInterval in nim

我有以下代码,其中 运行 在一个间隔中传递的过程,return 一个 clearInterval 过程来停止 运行,如下所示:

proc runInterval(cb: proc, interval: int): Future[proc()] {.async.} =
  var stop_run = false
  while not(stop_run):
    await sleepAsync(intv)
    cb()
  
  proc clearInterval() =
    stop_run = true
  
  return clearInterval

proc in_interval() =
  echo "hahah"

let clearInterval = runInterval(in_interval, 1000) # run the in_interval proc every 1 second
clearInterval() # stop in_interval (can't compile)
runForever()

我怀疑 运行Interval 的类型注释不正确,因为

: 未来 [proc()] {.async.} ,但我不知道如何定义 returnning 类型为 proc 以及 {.async.} 的 proc?

正如@dom96 所建议的那样,您应该像这样使闭包 return 布尔值:

import asyncdispatch
import random

proc runInterval(cb: proc, interval: int) {.async.} =
  var stop_run = false
  while not stop_run:
    await sleepAsync(interval)
    if not cb():
      break 

proc in_interval(): bool =
  if rand(1..6) > 2:
    echo "lucky"
    true
  else:
    echo "unlucky"
    false


randomize()

discard runInterval(in_interval, 500)

runForever()

可以通过将 while 循环包装在它自己的异步过程中并将异步从 runInterval 过程中移除到直接 return clearInterval:

import asyncdispatch

proc runInterval(cb: proc, interval: int): proc() =
  var stop_run = false

  proc clearInterval() =
    stop_run = true

  proc runIntervalLoop() {.async.} =
    while not(stop_run):
      await sleepAsync(interval)
      cb()

  asyncCheck runIntervalLoop()
  
  return clearInterval

proc in_interval() =
  echo "hahah"

proc process {.async.} =
  let clearInterval = runInterval(in_interval, 1000) # run the in_interval proc every 1 second
  await sleepAsync(3000)
  echo "Finished sleeping"
  clearInterval()
  echo "Cleared interval"

waitFor process()