164

How do you pause an R script for a specified number of seconds or miliseconds? In many languages, there is a sleep function, but ?sleep references a data set. And ?pause and ?wait don't exist.

The intended purpose is for self-timed animations. The desired solution works without asking for user input.

Tomas
  • 54,903
  • 47
  • 225
  • 361
Dan Goldstein
  • 23,149
  • 17
  • 36
  • 41
  • 6
    @Ricardo, we had a whole discussion on this with Joshua and others and we finally agreed that both "pause" and "sleep" should be in the title. The final title was result of a compromise. And you just step in and *without any argument why your title is better* rollback to previous revision? Adding "sleep" to the title makes the question much easier to find, because "sleep" is in many languages and there is a high probability that users will search for it. Current title contains a lot of word balast and the important keyword is missing. *What was the purpose of your rollback?* – Tomas Jul 22 '13 at 05:29
  • Google "r sleep" couldn't find it, tried to fix it. – Tomas Jan 17 '14 at 15:03

2 Answers2

173

See help(Sys.sleep).

For example, from ?Sys.sleep

testit <- function(x)
{
    p1 <- proc.time()
    Sys.sleep(x)
    proc.time() - p1 # The cpu usage should be negligible
}
testit(3.7)

Yielding

> testit(3.7)
   user  system elapsed 
  0.000   0.000   3.704 
Gavin Simpson
  • 164,190
  • 25
  • 377
  • 440
Dirk Eddelbuettel
  • 347,098
  • 55
  • 623
  • 708
17

Sys.sleep() will not work if the CPU usage is very high; as in other critical high priority processes are running (in parallel).

This code worked for me. Here I am printing 1 to 1000 at a 2.5 second interval.

for (i in 1:1000)
{
  print(i)
  date_time<-Sys.time()
  while((as.numeric(Sys.time()) - as.numeric(date_time))<2.5){} #dummy while loop
}
rbtj
  • 311
  • 2
  • 6
  • the Sys.sleep() function did not work in my use case, and this was the only way I was able to manage producing the necessary delay. – Pake Apr 03 '20 at 20:53