# NOT RUN {
## Call 10 times a second, cancel with 1/10 probability
counter <- 0L
do <- function() {
  cb <- function() {
    cat("called\n")
    counter <<- counter + 1L
    if (runif(1) < 0.1) t$cancel()
  }
  t <- async_timer$new(1/10, cb)
}
run_event_loop(do())
counter
## Error handling
counter <- 0L
do <- function() {
  cb <- function() {
    cat("called\n")
    counter <<- counter + 1L
    if (counter == 2L) stop("foobar")
    if (counter == 3L) t$cancel()
  }
  t <- async_timer$new(1/10, cb)
  handler <- function(err) {
    cat("Got error:", sQuote(conditionMessage(err)), ", handled\n")
  }
  t$listen_on("error", handler)
}
run_event_loop(do())
counter
## Error handling at the synchonization point
counter <- 0L
do <- function() {
  cb <- function() {
    cat("called\n")
    counter <<- counter + 1L
    if (counter == 2L) stop("foobar")
    if (counter == 3L) t$cancel()
  }
  t <- async_timer$new(1/10, cb)
}
tryCatch(run_event_loop(do()), error = function(x) x)
counter
# }
Run the code above in your browser using DataLab