JavaScript:D3 .duration()

andersooi's avatar
Published Dec 19, 2023
Contribute to Docs

The .duration() method sets the time for which a transition lasts. This method is crucial for creating animated visualizations as it allows developers to control the length of an animation. It accepts a single argument representing the duration in milliseconds for the transition.

  • Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.
    • Includes 27 Courses
    • With Professional Certification
    • Beginner Friendly.
      95 hours
  • Learn how to create bar charts with D3, the popular interactive data visualization library.
    • With Certificate
    • Intermediate.
      1 hour

Syntax

transition().duration(t)
  • t: It is the duration of the animation and the only argument taken by the .duration() method. If not specified, the default duration value is set to 250ms for the transition.

Example

Below is an example of how to use the .duration() method to create a transition effect (color change) on an SVG circle:

function changeColor() {
// Select the circle element by its ID
d3.select('#myCircle')
.transition() // Start a transition
.duration(1000) // Set the duration to 1 second
.attr('fill', 'steelblue'); // Change the fill color to steelblue
console.log('Color changed successfully');
}

In this example, the selection identified by myCircle will smoothly transition its color to steelblue. Once the transition is complete, a console message will confirm its completion.

The following gif shows the transition effect on an SVG circle when the function is called:

D3 transition effect on SVG circle

The output in the console is as follows:

"Color changed successfully"

All contributors

Contribute to Docs

Learn JavaScript:D3 on Codecademy

  • Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.
    • Includes 27 Courses
    • With Professional Certification
    • Beginner Friendly.
      95 hours
  • Learn how to create bar charts with D3, the popular interactive data visualization library.
    • With Certificate
    • Intermediate.
      1 hour