Search code examples
rwhile-loopconditional-statements

While condition does not break


I have the following code in R, and I believe it should break immediately. Instead it runs until number_of_retries is reached. But trying it manually "status <- run_request_and_writedb()" makes status TRUE, and is.null(status ) evaluates to FALSE, which should break the while loop if not both conditions are met. What am I missing here, or do I fundamentally misunderstand while conditions?

run_request_and_writedb <- function() {
      return(TRUE)
}

  ## Try the function a few times
  # return value is null
  status <- NULL
  # number of attempts at start
  attempt <- 1
  number_of_retries <- 3
  
  while( is.null(status) && attempt <= number_of_retries ) {
    try(
      status <- run_request_and_writedb()
    )
    attempt <- attempt + 1
    Sys.sleep(10)
  }

Solution

  • It's not a matter of terminating the while loop, but Sys.sleep(10) gives you the illusion that the while loop is endless (unless you are sufficiently patient and wait for 10 seconds).

    Description

    Suspend execution of R expressions for a specified time interval.

    Usage

    Sys.sleep(time)

    Arguments

    time The time interval to suspend execution for, in seconds.

    When you remove Sys.sleep(10), you can see that your code exits the loop

    ## Try the function a few times
    # return value is null
    status <- NULL
    # number of attempts at start
    attempt <- 1
    number_of_retries <- 3
    
    while (is.null(status) && attempt <= number_of_retries) {
        status <- run_request_and_writedb()
        attempt <- attempt + 1
    }
    

    or add break immediately before Sys.sleep(10)

    ## Try the function a few times
    # return value is null
    status <- NULL
    # number of attempts at start
    attempt <- 1
    number_of_retries <- 3
    
    while (is.null(status) && attempt <= number_of_retries) {
        status <- run_request_and_writedb()
        attempt <- attempt + 1
        break
        Sys.sleep(10)
    }