1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
library(iterators)
# Returns an iterator that limits another iterator based on time
itimer <- function(it, time) {
it <- iter(it)
start <- proc.time()[[3]]
nextEl <- function() {
current <- proc.time()[[3]]
if (current - start >= time)
stop('StopIteration')
nextElem(it)
}
obj <- list(nextElem=nextEl)
class(obj) <- c('itimer', 'abstractiter', 'iter')
obj
}
# Create a iterator that counts for one second
it <- itimer(icount(Inf), 1)
tryCatch({
repeat {
print(nextElem(it))
}
},
error=function(e) {
cat('timer expired\n')
})
|