3

I'm creating reveal.js slides in RStudio and I'd like to include a slide with a countdown timer for a 10 min break halfway through the presentation.

I have an externaml html file with the timer code (below) and use a Rmd code chunk to include it in the slide:

```{r, echo=FALSE}
htmltools::includeHTML("timer.html")
```

The problem is that the timer starts when the presentation file is open and I need it to start when the particular slide shows up.

I tried playing around with Reveal.addEventListener() as suggested here but I can't make it work (I don't really know javascript).

I'd really appreciate any suggestions. In particular, if anyone knows how to do all of this in RStudio without having to subsequently manually edit the presentation html, that would be great. Thanks!

<h1><section id="timer"></section></h1>

<script>
// 10 minutes from now
var current_time = Date.parse(new Date());
var deadline = new Date(current_time + 10*60*1000);

Number.prototype.pad = function(size) {
  var s = String(this);
  while (s.length < (size || 2)) {s = "0" + s;}
  return s;
}

var x = setInterval(function() {
var now = new Date().getTime();
var t = deadline - now;
var minutes = Math.floor((t % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((t % (1000 * 60)) / 1000);
document.getElementById("timer").innerHTML = minutes.pad(2) + " : " + seconds.pad(2);
    if (t < 0) {
        clearInterval(x);
        document.getElementById("timer").innerHTML = "Time is up";
    }
}, 1000);

</script>
Milan Valášek
  • 571
  • 3
  • 10
  • did you ever find a solution to this problem? – Ratnanil Mar 02 '22 at 14:56
  • 1
    I switched to `remark.js` but before I did, I just turned the code above into a function that got triggered by clicking on the timer element. If you have that kind of function, *e.g.,* `startTimer()`, then running it on slide change is simple. You just need `Reveal.addEventListener("slidechanged", function(e) { if (Reveal.getCurrentSlide().id === "timer") startTimer() });` N.B. This won't reset the timer if you navigate away from it and will start a new interval each time you show the slide which will mess up the timer. Dealing with that shouldn't be hard though... – Milan Valášek Mar 02 '22 at 17:17

0 Answers0