'Break out of loop and continue with next iteration after a certain time?

Hi supposed I have something like this.

s = c( 1, 10, 20, 2, 3, 300 )
for ( i in 1:1000 ){
  
  Sys.sleep( sample ( s, 1 ))
  # break if it longer than 20 seconds? 
  print ( "done") 
}

What I want to the loop to do is to break and continue if a command takes more than 20 secs?

thanks.

r


Solution 1:[1]

Maybe this serves your purpose:

for ( i in 1:1000 ){
      wait <- sample ( s, 1 )
      if(wait > 20) break
      else {
          # print(wait)  
          Sys.sleep( wait)
          print ( "done") 
      }
  }

print(wait) is an optional way to know the sampled wait.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Abdur Rohman