I'm creating a game in Shiny that needs accurate measurements of the time a user clicks on a photo (ideally precise down to the hundredth of a second, but a tenth of a second would work too).
The server time is a function of the internet connection, which can be slow with latency and what not. Therefore, I'd like to access the time on the client's machine.
I am able to retrieve the server system time at a button press. I'm also able to get the client's system time at the launch of the shiny app (using java), but I'm unable to retrieve the client's system time for each click. However, I'm getting what seems to be NA on the first click and then the time of the previous click. Any thoughts?
(The example below is based on a button click for the sake of simplicity.)
EDITED (I implemented Shiny.onInputChange
and changed the time parsing)
library(shiny)
library(shinyjs)
if (interactive()) {
ui <- shinyUI(
fluidPage(
useShinyjs(),
verbatimTextOutput("clientTime"),
verbatimTextOutput("serverTime"),
HTML('<input type="text" id="client_time" name="client_time" style="display: none;"> '),
actionButton("btn1","Click to see times")
))
server <- function(input, output){
# this block fires each time we receive a message from JavaScript
output$text <- renderText({
req(input$count)
paste("you clicked", input$count, "times on the RStudio ball")
})
observeEvent(input$btn1,
{
shinyjs::runjs(
'
$(function() {
var time_now = new Date();
Shiny.onInputChange("client_time", time_now)
});
')
times <- as.POSIXct(
input$client_time,
format = "%Y-%m-%dT%H:%M:%OS")
times <- paste("Client Time:", format(times, "%Y-%m-%d %H:%M:%OS3"))
output$clientTime <- renderText(times)
servertimes <- Sys.time()
servertimes <- paste("Server Time:", format(servertimes, "%Y-%m-%d %H:%M:%OS3"))
output$serverTime <- renderText(servertimes)
})
}
shinyApp(ui = ui, server = server) }