🏠 back to Observable

how to restart d3.interval when re-running cell

I’m aminating locations on a map, and using d3.interval to transition the date ticker text (at the same speed as the animation). When I reload the cell, the animation restarts as it should but the ticker goes wacky, as it seems to start a new counter, while the old one is still going (from before I re-ran the cell).

I’d like users to be able to rerun at anytime, using the replay button, how do I break out of d3.interval when the button is pressed?

https://observablehq.com/d/9dd27a6dd374735e@2149/

This is the d3.interval code I’m using

    d3.select(".calendar-date")
      .transition()
      .text(
        bear_data[0].properties.dates[count].toLocaleString(undefined, {
          year: "numeric",
          month: "short",
          day: "numeric"
        })
      );
    count++;
  }, (speed * 1000) / bear_data[0].properties.dates.length)

Figured out that by changing to

while (count < bear_data[0].properties.dates.length) {
      
   d3.select(".calendar-date")
      .transition()
      .text(
        bear_data[0].properties.dates[count].toLocaleString(undefined, {
          year: "numeric",
          month: "short",
          day: "numeric"
        })
      );
   
    await Promises.tick(
      (speed * 1000) / bear_data[0].properties.dates.length,
      ++count
    );
  
  }

and putting it at the bottom of the cell, things worked when replayed