Nadeem Hussain
Nadeem Hussain

Reputation: 219

How to restart a loop with eval with timeout in R?

while (!exists("j")) {
    i <- 1

    repeat {
        tryCatch(expr = {
            print(i)

            raw.result <- evalWithTimeout(Sys.sleep(i), timeout = 3)

            if (i == 1) {
                j <- i
            } else {
                j <- c(j, i)
            }

            i <- i + 1
        }, TimeoutException = function(ex) {
            rm("j")
        })
    }
}

The above code is getting stuck at i=4 and keeps executing the function for i=4, however I want it to restart from i=1, whenever there is an error.

Can someone please guide on where am I doing it wrong?

Upvotes: 1

Views: 944

Answers (1)

Jav
Jav

Reputation: 2313

In your codeTimeoutException is unable to find j as it is evaluated in a different environment. Even if it was able to find it, nothing would change. As tryCatch is stopping an error from breaking a repeat loop, thus repeat will continue with the current i. You could explicitly break out from the repeat, but in that case you have deleted j, thus your while will stop.

I am not quite sure why you need while loop here.

Here is a modification of your code that will work as you want. Fist explicitly set i <- 1, and rest it again to i <<-1 (Note <<- as i is one environment above tryCatch).

i <- 1

repeat {
  tryCatch(
    expr = {
      print(i)

      raw.result <- R.utils:evalWithTimeout(Sys.sleep(i), timeout = 3)

      if (i == 1) {
        j <- i
      } else {
        j <- c(j, i)
      }

      i <- i + 1
    },
    TimeoutException = function(ex) {
      i <<- 1
    }
  )
}

Upvotes: 3

Related Questions