Using Sys.sleep in R function to delay multiple ou

2019-03-03 11:20发布

问题:

I have this function:

func<-function(name){
    paste("Your name is. . .")
    Sys.sleep(1.5)
    paste(name)
}

This function obviously won't work, but the idea is to wait 1.5 seconds between each output.

For example, calling func("Catherine") should print to console:

[1] "Your name is..."

Then wait 1.5 seconds, and print:

[1] "Catherine"

回答1:

Just wrap your desired output in a print statement:

func<-function(name){
  print("Your name is. . .")

  Sys.sleep(1.5)

  print(name)
}

#Execute Function
func("Martin")

[1] "Your name is. . ."
[1] "Martin"


回答2:

I'm not quite sure what the question is, but this produces the behavior you are talking about.

func <- function(name)
{
print("Your name is. . .")
flush.console()
Sys.sleep(1.5)
print(name)
}

> func('Test')
[1] "Your name is. . ."
[1] "Test"
> 


标签: r function sleep