Q:

How to best create a Timer Function in R

I'm trying to create a function in R that returns for the first x seconds after the function call 1, the next x seconds 0, the next x seconds 1 again,...the whole procedure should stop after another time interval or after n iterations. I want to do this with one function call.
I read about the package tcltk which apparently entails some possibilities to create such "timer" functions, however I did not find enough explanations to sort out my issue. 
Could you advise me where to find a good manual that explains tcl in context with R? Do you have other ideas how to create such a function in an efficient way?
Thanks a lot for your help. 

A:

If I understood you correctly, you are trying to create a function that will return 1 whenever it is called in the first x secs, then return 0 whenever it's called in the next x secs, then return 1 over the next x secs, etc. And after a certain total time, it should be "done", maybe return -1?
You could do this using the following function that will "create" a function with any desired interval:
flipper <- function(interval=10, total = 60) {
  t0 <- Sys.time()
  function() {
    seconds <- round(as.double( difftime(Sys.time(), t0, u = 'secs')))
    if(seconds > total)
      return(-1) else
    return(trunc( 1 + (seconds / interval ) ) %% 2)
  }
}

You can use this to create a function that alternates between 0 and 1 every 10 secs during the first 60 seconds, and returns -1 after 60 seconds:
> flp <- flipper(10,60)

Now calling flp() will have the behavior you are looking for, i.e. when you call flp() during the next 60 secs, it will alternate between 1 and 0 every 10 secs, then after 60 secs it will just return -1.

A:

Sys.sleep from base could not be a solution?
E.g.: stop every 10th iteration in a loop for 10 seconds:
for (i in 1:100) {
    # do something
    if ((i %% 10) == 0) {
        Sys.sleep(10)
    }
}

A:

May I also suggest:
Timer 1 
library(data.table)

begin.time <- proc.time()
timetaken(begin.time)

Timer 2   
library(matlab)

tic(gcFirst=FALSE)
toc(echo=TRUE)

Both are excellent choices for timers

