nnn
nnn

Reputation: 5165

How to interrupt at loop end

How can I write a loop in R so that if I press esc it stops not in the middle but at the end of the loop? So to say I want to define points where it is safe to interrupt the loop.

I am running an iteration with a plot every second. If the visual results don't develop in the right direction, I want to be able to interrupt the iteration, tweak some parameters and continue the iteration. Now I am doing this by pressing esc or the stop button in the GUI. But this corrupts some data, because the interrupt takes place in the middle of a calculation. So I am not able to continue the iteration.

Upvotes: 3

Views: 165

Answers (1)

BrodieG
BrodieG

Reputation: 52647

Here is an option using withRestarts and hijacking the "abort" restart. Try running the code and hitting "ESC" while the loop is going:

# Make up a task that takes some time

task_to_perform_in_loop <- function() for(i in 1:100) Sys.sleep(0.01)

# Run task in loop
{
  stopAtEnd <- FALSE
  for(i in 1:5) {
    cat("Loop #", i, "\n", sep="")
    withRestarts(
      task_to_perform_in_loop(),
      abort=function(e) {
        message("Will stop when loop complete")
        stopAtEnd <<- TRUE
      }
    )  
  }
  if(stopAtEnd) stop("Stopping After Finishing Loop")  
  cat("Continuing After Finishing Loop")
}

Just keep in mind this will prevent you from truly exiting the loop short of sending a kill command to R.

Upvotes: 2

Related Questions