Prayush Dawda
Prayush Dawda

Reputation: 542

Is it possible to vary the time interval while the timer is running in d3.js?

I want to be able to adjust the time interval between the callbacks. I'm using d3's interval in the following manner:

let timeInterval = 500;
d3.interval(callback, timeInterval);

Now, at some point during the execution, I want to be able to adjust the timeInterval's value (via user input) and have it reflect in the speed at which the subsequent callbacks will be executed. Is this possible, and if so, how?

Upvotes: 3

Views: 240

Answers (2)

altocumulus
altocumulus

Reputation: 21578

The easiest way to change an interval's behavior—including its timing—is calling the .restart() method on it. Since a d3.interval() is just a wrapped d3.timer() which is executed periodically it also features said .restart() method.

# timer.restart(callback[, delay[, time]]) <>

Restart a timer with the specified callback and optional delay and time. This is equivalent to stopping this timer and creating a new timer with the specified arguments, although this timer retains the original invocation priority.

This can be done along the following lines:

const callback = console.log;
const interval = d3.interval(callback, 500);  // initial timing 500ms
interval.restart(callback, 1000);             // updated timing 1000ms
<script src="https://d3js.org/d3.v6.js"></script>

Upvotes: 2

AKX
AKX

Reputation: 168863

d3.interval() apparently returns the timer object that was created.

You can stop the old timer and start a new one:

var intervalTimer;
// ... other code ...
intervalTimer = d3.interval(callback, 500);
// ... other code ...
intervalTimer.stop();
intervalTimer = d3.interval(callback, 100);
// ...

Upvotes: 0

Related Questions