I don’t use jQuery, neither in regular webapps nor in Apps Script HtmlService apps. No particular reason – I just prefer to use vanilla JavaScript. I often use d3.js, mainly for visualization as in these examples elsewhere on this site. Aside from being great for complicated visualizations, d3 also has a great many of the Dom management shortcuts you use jQuery for and is very useful for SVG transitions. In some ways then, if you want to use a framework or helper library, then D3 is actually a pretty good choice for its breadth of capabilities. The problem with D3 though, is that if you only use it from time to time, it’s hard to get back into it again as it’s very different than what we are used to. In my BigQuiz app I needed some nice timers, so I decided to write a reusable one in D3. What’s more, it uses promises to indicate expiry or interruption, which allows elegant handling of expiries or interruptions.  SVG transitions don’t all ow pausing and resuming of transitions, but this timer invisibly supports pause/resume through promise manipulation, which you’ll see more of later. You can use the codepen
below to run it and take a look at the code. Once you’ve read up the documentation following you may want to play around with the options too. 

DashTimer

To use this you’ll need these scripts


My example code uses a material design framework, so I include this. You may be using some other css framework for this, or none at all. It’s up to you whether you include this or something like it.

<script src=”//cdnjs.cloudflare.com/ajax/libs/es6-promise/3.2.1/es6-promise.min.js”></script>

For the examples you can fork the codepen above and try all these out as we go along. I’ve included all the settings in each example to replicate the illustration so you can just paste it in.

Creating a timer

var an = new DashTimer(div);

where div is either an element or a selector for an element (eg ‘#mydiv’)

Options

These control the behavior of the timer, and also provide defaults for each of the animated items in the timer. A timer can contain multiple arcs, but more on that later. DataEach arc in the timer has data to describe the transition it needs to during the lifetime of the timer – this can be things like displayed values, fill colors, width and so on.

Default values

If you run a timer with no options or data specified, with this container

<div id=”timer”></div>

You’ll get something that looks like this, that takes 5 seconds to complete.

Multiple arcs

Although it looks like there is only one arc there, there are actually 2, but they have the same characteristics to they move at the same time. I usually call them main and the other shadow.
A small change to the data will show both.

var dt = new DashTimer(‘#timer’).init().setData( [{start:{angle:1,fill:’#eee’},finish:{angle:0,fill:’#eee’}}, {}]).start();

Showing values

Values can be shown throughout the transition like this. Here I’ve added {values:show} to the dataset for the second arc.

var dt = new DashTimer('#timer').init().setData([{
  immediate: {
    angle: true
  },
  start: {
    angle: 1,
    fill: '#eee'
  },
  finish: {
    angle: 0,
    fill: '#eee'
  }
}, {
  values: {
    show: true
  }
}]).start();

Setting values

The values that are being shown are the default ones – 0-100, but you can of course use any values. This example starts at 5000 and goes down to 1. Notice that I’ve also change the default duration to 20000 milliseconds by passing that to the .start() method.

var dt = new DashTimer('#timer').init().setData([{
  immediate: {
    angle: true
  },
  start: {
    angle: 1,
    fill: '#eee'
  },
  finish: {
    angle: 0,
    fill: '#eee'
  }
}, {
  values: {
    show: true
  },
  start: {
    value:5000
  },
  finish: {
    value:1
  }
}]).start(20000);

Fill colors

Up till now I’ve been using the default fill colors for the main arc which gradually transition between the start and finish colors. Here I want a constant red.

var dt = new DashTimer('#timer').init().setData([{
  immediate: {
    angle: true
  },
  start: {
    angle: 1,
    fill: '#eee'
  },
  finish: {
    angle: 0,
    fill: '#eee'
  }
}, {
  values: {
    show: true
  },
  start: {
    value:5000,
    fill:'red'
  },
  finish: {
    value:1,
    fill:'red'
}]).start(20000);

Setting defaults

The defaults of any of these values can be set, by passing them in the .init() stage.

var dt = new DashTimer('#timer').init({
  start:{
    fill:'green'
  },
  finish: {
    fill:'red'
  }
}).setData([{
  immediate: {
    angle: true
  },
  start: {
    angle: 1,
    fill: '#eee'
  },
  finish: {
    angle: 0,
    fill: '#eee'
  }
}, {
  values: {
    show: true
  },
  start: {
    value:5000,
  },
  finish: {
    value:1,
  }
}]).start(20000);

Arc size

The size of the timer can be set using innerRatio and outerRatio. These refer to the proportion of the overall size of the visualization of the inner and outer arc. The difference between them sets the width of the filled area.

var dt = new DashTimer('#timer').init({
  start:{
    fill:'green',
    innerRatio:.7,
    outerRatio:1
  },
  finish: {
    fill:'red',
    innerRatio:.7,
    outerRatio:1
  }
}).setData([{
  immediate: {
    angle: true
  },
  start: {
    angle: 1,
    fill: '#eee'
  },
  finish: {
    angle: 0,
    fill: '#eee'
  }
}, {
  values: {
    show: true
  },
  start: {
    value:5000,
  },
  finish: {
    value:1,
  }
}]).start(20000);

Transitioning arc size

The start and finish ratios can be different, which will have the effect of an expanding arc as it the transition progresses.

var dt = new DashTimer('#timer').init({
  start:{
    fill:'green',
    innerRatio:.7,
    outerRatio:1
  },
  finish: {
    fill:'red',
    innerRatio:.7,
    outerRatio:1
  }
}).setData([{
  immediate: {
    angle: true
  },
  start: {
    angle: 1,
    fill: '#eee'
  },
  finish: {
    angle: 0,
    fill: '#eee'
  }
}, {
  values: {
    show: true
  },
  start: {
    value:5000,
  },
  finish: {
    value:1,
  }
}]).start(20000);

The above transition starts thin

and becomes thick

Start and finish angles

The start and finish angles control where the arc starts and finishes

var dt = new DashTimer('#timer').init({
  start:{
    fill:'green',
    innerRatio:.9,
    outerRatio:1
  },
  finish: {
    fill:'red',
    innerRatio:.3,
    outerRatio:1
  }
}).setData([{
  immediate: {
    angle: true
  },
  start: {
    angle: 1,
    fill: '#eee'
  },
  finish: {
    angle: 0,
    fill: '#eee'
  }
}, {
  values: {
    show: true
  },
  start: {
    angle:.25
  },
  finish: {
    angle:1.25,
  }
}]).start(20000);

This one starts and finishes at 3 o’clock.

Timer size

The size of the timer is controlled by the width and height – which for this kind of viz are normally set to the same thing.

var dt = new DashTimer('#timer').init({
  height:150,
  width:150,
  start:{
    fill:'green',
    innerRatio:.9,
    outerRatio:1
  },
  finish: {
    fill:'red',
    innerRatio:.3,
    outerRatio:1
  }
}).setData([{
  immediate: {
    angle: true
  },
  start: {
    angle: 1,
    fill: '#eee'
  },
  finish: {
    angle: 0,
    fill: '#eee'
  }
}, {
  values: {
    show: true
  },
  start: {
    angle:.25
  },
  finish: {
    angle:1.25,
  }
}]).start(20000);

Here’s a bigger one. Notice that since the inner and outer ratios are proportions of these sizes, then they don’t need to be changed even if the timer overall size changes.

Decorating values

The values are updated at each transition tick. Normally this would lead to floating point results. You can decorate the values before they are shown by means of a decorator function. The default one rounds the values. This one only changes the value every multiple of 10.

var dt = new DashTimer('#timer').init({
  start:{
    fill:'green',
    innerRatio:.9,
    outerRatio:1
  },
  finish: {
    fill:'red',
    innerRatio:.3,
    outerRatio:1
  }
}).setData([{
  immediate: {
    angle: true
  },
  start: {
    angle: 1,
    fill: '#eee'
  },
  finish: {
    angle: 0,
    fill: '#eee'
  }
}, {
  values: {
    show: true,
    decorate:function (d) {
      return Math.floor(d/10) * 10;
    }
  },
  start: {
    angle:.25
  },
  finish: {
    angle:1.25,
  }
}]).start(20000);

Partial transition

You can specify start and finish points for the transition

var dt = new DashTimer('#timer').init({
  start:{
    fill:'green',
    innerRatio:.9,
    outerRatio:1
  },
  finish: {
    fill:'red',
    innerRatio:.3,
    outerRatio:1
  }
}).setData([{
  immediate: {
    angle: true
  },
  start: {
    angle: 1,
    fill: '#eee'
  },
  finish: {
    angle: 0,
    fill: '#eee'
  }
}, {
  values: {
    show: true,
    decorate:function (d) {
      return Math.floor(d/10) * 10;
    }
  }
}]).start(20000,0,.67);

Classes

You can apply classes to text like this

var dt = new DashTimer('#timer').init({
  start:{
    fill:'green',
    innerRatio:.9,
    outerRatio:1
  },
  finish: {
    fill:'red',
    innerRatio:.3,
    outerRatio:1
  },
  values: {
    show: true,
    decorate:function (d) {
      return Math.floor(d/10) * 10;
    },
    classes:"mui--text-light-secondary mui--text-caption"
  }
}).setData([{
  immediate: {
    angle: true
  },
  start: {
    angle: 1,
    fill: '#eee'
  },
  finish: {
    angle: 0,
    fill: '#eee'
  }
},{ 
  values:{
    show:true
  }
}]).start(20000,0,.67);

dataName

You can give names to each of the arcs. This will help later to patch and examine transition data.

  values: {
    show: true,
    classes:"mui--text-light-secondary mui--text-caption"
  }
}).setData([{
  dataName:'shadow',
  immediate: {
    angle: true
  },
  start: {
    angle: 1,
    fill: '#eee'
  },
  finish: {
    angle: 0,
    fill: '#eee'
  }
},{ 
  dataName:'main',
  values:{
    show:true
  }
}]).start(20000);

callback

You can set up a callback to be executed at each tick of the transition.

var dt = new DashTimer('#timer').init({
  values: {
    show: true,
    classes:"mui--text-light-secondary mui--text-caption"
  },
  callback: function (d,dash,tick) {
    console.log (d.dataName + ':' + d.value + " tick " + tick);
  }
}).setData([{
  dataName:'shadow',
  immediate: {
    angle: true
  },
  start: {
    angle: 1,
    fill: '#eee'
  },
  finish: {
    angle: 0,
    fill: '#eee'
  }
},{ 
  dataName:'main',
  values:{
    show:true
  }
}]).start(20000);

Which will produce a log like this. This is useful for debugging, but you can do anything you wany here – for example update another element or perhaps change the behavior of the timer.

Methods

.start(duration, start , finish)

Transitions are started with the start method. Start and finish (default 0 and 1) control the coverage of the transition, and duration is the length in milliseconds. Start returns a promise. More on this later.

.pause()

Temporarily pause the transition

.resume()

Resume after a pause

.setProgress(progress)

set progress to given value between 0 and 1. Transition is stopped.

.cancel()

cancel the in progress transition.

.isPaused()

is the transition paused

.isFinished()

is it finished

.isCancelled()

was it cancelled

.isRunning()

is active and not paused

.init(options)

set default values for each arc

.setData([data])

specific values for each arc

.getData()

get the current data for each arc. The default values will have been applied.

.getItem(dataName)

get the data associated with the named arc. This is why it’s useful to give a dataName in the data for each arc. This is useful to dynamically change some values, for example (although not all values are changeable in the middle of a transition).

dt.getItem("shadow").start.value = 200;

.getControl()

get the control values for the transition. These should not be changed but may be useful

.getVizInfo()

get the D3 control structures in case you want to do some D3 layout customization

.getProgress()

get the current viz progress between 0 and 1

Transition ends and interruptions. 

Timers and asynchronous and cannot be conviently placed inline in code. The DashTimer uses Promises which makes teh whole thing very manageable. Here’s typically how to use it.

var timer = new DashTimer('#timer').init().setData();
timer.start(2000).then (
  function (dt) {
    console.log (dt.getControl().name + ' ran out of time or was set');
  },
  function (dt) {
    console.log (dt.getControl().name + ' was cancelled');
  });

If the timer runs out of time, or if a setProgress() is called then the promise is resolved. If a cancel() is called then the promise is rejected as above. 

Pauses and resumptions

timer.pause() and timer.resume() can be used as often as you like during the lifetime of a transition. Pause time does not count towards the transitions. D3 does not support interrupting transitions directly,  and in fact DashTimer runs separate transitions in the background, appropriate for the stage that the master transition was at when it was paused.  Pausing neither resolves nor rejects the promise associated with the master transition. Only setProgress, cancel and time expiry cause the master transition promise to be resolved or rejected.

Easing

Easing is a way of making transitions more pleasant, often by slowing down a bit at the beginning and end. Although D3, and therefore DashTimer support multiple easing methods, the timing will be inaccurate if there has been pausing and resuming during the lifetime of the transition. So in other words, you can use any of the D3 easing methods but be careful if you allow pausing. Easing is set as an option and by default is “linear”. See below in the default options list. 

Default options

here’s all the default options

{     // default settings - many can be overridden in data for individual items
      height: 100,           // height of viz
      width: 100,            // width of viz (since a circle both are equal)
      ease: "linear",        // type of easing (pause/resume will only work reliably with linear)
      duration: 5000,        // tranistion duration
      callback:"",           // function (d, self) to call back on every transition step
      name: NAME + new Date().getTime(), // name of dashtimer
      start: {               // values at start of transition
        innerRatio: .8,      // diameter of inner circle relative to height
        outerRatio: .95,      // diameter of outer circle relative to height
        angle: 0,            // angle between 0 and 1
        fill: '#2196F3',     // fill color
        value: 0             // value to interpolate
      },
      finish: {              // values at end of transition
        innerRatio: .8,      // diameter of inner circle relative to height
        outerRatio: .95,     // diameter of outer circle relative to height
        angle: 1,            // angle between 0 and 1
        fill: '#FFC107',     // fill color
        value: 100           // value to interpolate
      },
      immediate: {           // if true then transition is skipped
        angle:false,         // the angle
      },
      values: {              // things to do with displaying values 
        classes: "",         // classes to apply separated by spaces
        styles: "text-anchor:middle;", // styles to apply separated by ;
        show: false,         // whether to show values
        decorate: function(d) {  // function to clean up data before displaying
          return Math.round(d); 
        }
      },           
      custom:{},             // should be used for any custom data to be carried around
      internal:{
        paused:false,
        progress:0,
        finished:true
      }                 
    }

Now that you’ve seen how that works, here’s a more complicated timer in the form of a clock. You can read the details of how to make that at Example of clock using d3 configurable timer, and by playing around with the codepen below

The code

The code is hosted on google cloud storage.
http://goinggas.com/cdn/dashtimer/v0.1/dashtimer.js

and is also on github, and below

/**
 * @constructor DashTimer
 * uses D3 to plot circular timer
 * @param {object|string} div the container for the viz an element or #name
 */
function DashTimer(div) {
  var TAU = 2 * Math.PI,
    NAME = "DashTimer";
  var self = this,
    data_, dash_,
    dInfo_ = {},
    div_ = Object(div) === div ? '#' + div.id : div;
  /**
   * initialize the arc data
   * @param {[object]} data the array of data for each arc
   * @param {object} [options=] the viz options
   * @return {DashTimer} self
   */
  self.setData = function(data, options) {
    // first time in, set up the containers
    if (!dash_) {
      self.init(options)
    }
    // set up values for d3
    data_ = (data || [{}, {}]).map(function(d, i) {
      var m = vanMerge_([dash_, d]);
      m.index = i;
      m.startAngle = m.start.angle * TAU;
      m.endAngle = m.finish.angle * TAU;
      m.start.innerRadius = dash_.height / 2 * m.start.innerRatio;
      m.start.outerRadius = dash_.height / 2 * m.start.outerRatio;
      m.innerRadius = m.start.innerRadius;
      m.outerRadius = m.start.outerRadius;
      m.finish.innerRadius = dash_.height / 2 * m.finish.innerRatio;
      m.finish.outerRadius = dash_.height / 2 * m.finish.outerRatio;
      m.value = m.start.value;
      m.static = {
        endAngle: m.immediate.angle,
        innerRadius: m.finish.innerRadius === m.start.innerRadius,
        outerRadius: m.finish.outerRadius === m.start.outerRadius,
        value: m.start.value === m.finish.value
      };
      m.dataName = m.dataName || NAME + i;
      return m;
    });
    d3.select(div_).html("");
    dInfo_.arc = d3.svg.arc();
    dInfo_.svg = d3.select(div_).append("svg")
      .attr("width", dash_.width)
      .attr("height", dash_.height)
      .append("g")
      .attr("transform", "translate(" +
        dash_.width / 2 + "," + dash_.height / 2 + ")");
    dInfo_.textElements = dInfo_.svg.append("text");
    (dash_.values.styles.split(";") || []).forEach(function(d) {
      if (d) {
        var s = d.split(":");
        if (s.length !== 2) throw 'invalid style ' + d;
        dInfo_.textElements.style(s[0], s[1]);
      }
    });
    if (dash_.values.classes) {
      dash_.values.classes.split(" ").forEach(function(d) {
        if (d) dInfo_.textElements.classed(d, true);
      });
    }
    dash_.internal.cancelled = dash_.internal.paused= dash_.internal.finished= false;
    resetPromise_();
    return self;
  };
  /**
   * initialize the arcs
   * @param {object} options the viz options
   * @return {DashTimer} self
   */
  self.init = function(options) {
    // merge default settings with given
    dash_ = vanMerge_([{     // default settings - many can be overridden in data for individual items
      height: 100,           // height of viz
      width: 100,            // width of viz (since a circle both are equal)
      ease: "linear",        // type of easing (pause/resume will only work reliably with linear)
      duration: 5000,        // tranistion duration
      callback:"",           // function (d, self) to call back on every transition step
      name: NAME + new Date().getTime(), // name of dashtimer
      start: {               // values at start of transition
        innerRatio: .8,      // diameter of inner circle relative to height
        outerRatio: .95,      // diameter of outer circle relative to height
        angle: 0,            // angle between 0 and 1
        fill: '#2196F3',     // fill color
        value: 0             // value to interpolate
      },
      finish: {              // values at end of transition
        innerRatio: .8,      // diameter of inner circle relative to height
        outerRatio: .95,     // diameter of outer circle relative to height
        angle: 1,            // angle between 0 and 1
        fill: '#FFC107',     // fill color
        value: 100           // value to interpolate
      },
      immediate: {           // if true then transition is skipped
        angle:false,         // the angle
      },
      values: {              // things to do with displaying values 
        classes: "",         // classes to apply separated by spaces
        styles: "text-anchor:middle;", // styles to apply separated by ;
        show: false,         // whether to show values
        decorate: function(d) {  // function to clean up data before displaying
          return Math.round(d); 
        }
      },           
      custom:{},             // should be used for any custom data to be carried around
      internal:{
        paused:false,
        progress:0,
        finished:true
      }                 
    }, options || {}]);
    return self;
  };
  /**
   * causes the timer to resolve from outside
   * @return {DashTimer} self
   */
  self.resolve= function() {
    dash_.internal.paused = false;
    dash_.internal.finished = true;
    dash_.mp.resolve(self);
    return self;
  };
  /**
   * causes the timer to reject from outside
   * @return {DashTimer} self
   */
  self.reject = function() {
    dash_.internal.paused = false;
    dash_.internal.finished = true;
    dash_.mp.reject(self);
    return self;
  };
  /**
   * pauses the timer right now
   * timeout promise is not resolved or rejected
   * @return {DashTimer} self
   */
  self.pause = function() {
    if (self.isRunning()) {
      dash_.internal.paused = true;
      dInfo_.path.transition(dash_.name).duration(0);
    }
    return self;
  };
  /**
   * resumes at the last place paused at
   * if not paused, nothing happens
   * @return {Promise | null} a promise to th resumed run - not normally required
   */
  self.resume = function() {
    // this will return the master promise
    if (self.isPaused()) {
      return work_(
        dash_.internal.progress,
        dash_.internal.duration * (dash_.finishAt - dash_.internal.progress),
        dash_.finishAt
      );
    }
  };
  /**
  * kills any ongoing transition
  * does not fire any promises
  * @return {DashTimer} self
  */
  self.cancel = function() {
    //if there is oe on the go then kill it and reject the promise
    if (dash_.mp) {
      dash_.internal.cancelled = true;
      // this will cause a zero transition to cancel the current one
      dInfo_.path.transition(dash_.name).duration(0);
      self.reject();
    }
  }
   /**
   * start a new timer
   * @param {number} duration number of seconds to run he transition for
   * @param {[object]} [data=] replace the current data with this
   * @param {number} [start=0] start place
   * @param {number} [finish=1] finish place
   * @return {Promise} a promise that'll be resolved when it times out
   */
  self.start = function(duration,start,finish) {
    resetPromise_();
    dash_.internal.duration = fixDef_ (duration,dash_.duration);
    return work_(fixDef_ (start,0) , dash_.internal.duration, fixDef_ (finish,1));
  };
  /**
   * get the current data 
   * @return {[object]} the data
   */
  self.getData = function() {
    return data_;
  };
  /**
   * get the current data 
   * @param {string} dataName the data name
   * @return {object} the data
   */
  self.getItem = function(dataName) {
    return data_.reduce(function(p,c) {
      return c.dataName === dataName ? c : p;
    },null);
  };
  /**
   * get all the current control values
   * @return {object} the current control values
   */
  self.getControl = function() {
    return dash_;
  };
  /**
   * get all the current control values
   * @return {object} the current control values
   */
  self.getVizInfo = function() {
    return dInfo_;
  };
  /**
   * is the viz currenly paused
   * @return {boolean} is it paused
   */
  self.isPaused = function() {
    return dash_.internal.paused;
  };
  /**
   * is the viz currenly finished
   * @return {boolean} is it finished
   */
  self.isFinished = function() {
    return dash_.internal.finished;
  };
  /**
   * is the viz currenly running
   * @return {boolean} is it running
   */
  self.isRunning = function() {
    return !self.isFinished() && !self.isPaused();
  };
  /**
   * is the viz currenly cancelled
   * @return {boolean} is it running
   */
  self.isCancelled = function() {
    return dash_.internal.cancelled;
  };
  /**
   * get the current progress
   * @return {number} between 0 and 1
   */
  self.getProgress = function() {
    return dash_.internal.progress;
  };
  /**
   * set the progress immediately and stop the viz
   * the completion promise is rejected
   * @param {number} between 0 and 1 to set it to
   * @param {number} [duration=0] how long to take to do it
   * @return {Promise} the master promise
   */
  self.setProgress = function(progress, duration) {
    return work_(0, fixDef_ (duration ,0 ), progress);
  };
  /**
   * reset the paths for the arcs
   */
  function redoPath_() {
    // redo the path
    dInfo_.path = dInfo_.svg.selectAll("path").data(data_);
    // add the new data
    dInfo_.enter = dInfo_.path.enter().append("path")
      .attr("fill", function(d) {
        return d.start.fill
      })
      .attr("d", dInfo_.arc);
    // get rid of any old
    dInfo_.path.exit().remove();
  }
  /**
   * make  a new master promise
   * @return {DashTimer} self
   */
  function resetPromise_() {
    dash_.mp = {};
    dash_.mp.promise = new Promise(function(resolve, reject) {
      dash_.mp.reject = reject;
      dash_.mp.resolve = resolve;
    });
    return self;
  }
  /**
   * co-ordinate the work, and manage the completion promises
   * @param {number} start place to start at between 0 and 1
   * @param {number} duration number of seconds to run he transition for
   * @param {number} [finish=1] place to stop at between 0 and 1
   * @return {Promise} a promise that'll be resolved when it times out
   */
  function work_(start, duration, finish) {
    // tidy up from last time
    redoPath_();
    finish = fixDef_ ( finish,1);
    // we'll need this if resuming
    dash_.finishAt = finish;
    dash_.startAt = start;
    // this returns a promise that simply resolves the master promise
    show_(start, duration, finish)
      .then(
        function(expired) {
          self.resolve();
        },
        function(stopped) {
          // nothing to do here - we dont want to resolve or reject the master promise
          // because this was just a pause
        });
    // return the master promise
    return dash_.mp.promise;
  }
  /**
   * do the transition
   * @param {number} startAt place to start at between 0 and 1
   * @param {number} duration number of seconds to run he transition for
   * @param {number} finishAt place to stop at between 0 and 1
   * @return {Promise} a promise that'll be resolved when it times out
   */
  function show_(startAt, duration, finishAt) {
    dash_.internal.paused = dash_.internal.finished = dash_.internal.cancelled = false, dash_.internal.progress = 0;
    // this is a promise that will be resolved when the timer runs out
    return new Promise(function(resolve, reject) {
      // interpolation include any startat/finishat generated by a pause
      // this returns a closure with the modified interpolation function
      function rng(a, b) {
        return d3.interpolate(
          d3.interpolate(a, b)(startAt), d3.interpolate(a, b)(1)
        );
      }
      dInfo_.path.transition(dash_.name)
        .ease(dash_.ease)
        .duration(duration)
        .each("end", function(d, i) {
          if (i === data_.length - 1) {
            dash_.internal.finished = true;
            resolve(self)
          }
        })
        .attrTween("d", function(d) {
          // these interpolate closures for each of the transitioing values
          d.interpolate = {
            innerRadius: rng(d.start.innerRadius, d.finish.innerRadius),
            outerRadius: rng(d.start.outerRadius, d.finish.outerRadius),
            endAngle: rng(d.start.angle * TAU, d.finish.angle * TAU),
            value: rng(d.start.value, d.finish.value)
          };
          // returns a closure for each tick
          return function(t) {
            // if a puase has been called in the meantime
            // a transition pause is signalled by rejecting the promise
            if (self.isPaused()) reject(self);
            // statics mean that they dont transition
            Object.keys(d.interpolate).forEach(function(k) {
              if (!d.static[k]) d[k] = d.interpolate[k](t * finishAt);
            });
            dash_.internal.progress = (startAt + (1 - startAt) * t * finishAt);
            // callback if requested
            if(d.callback) d.callback(d , self , t);
            // show the interpolated value 
            if (d.values.show) {
              dInfo_.textElements.text(d.values.decorate(d.value));
            }
            return dInfo_.arc(d);
          };
        })
        .styleTween("fill", function(d) {
          return d3.interpolate(
            d3.interpolate(d.start.fill, d.finish.fill)(startAt),
            d3.interpolate(d.start.fill, d.finish.fill)(finishAt));
        });
    });
  };
  /**
   * recursively extend an object with other objects
   * @param {[object]} obs the array of objects to be merged
   * @return {object} the extended object
   */
  function vanMerge_(obs) {
    return (obs || []).reduce(function(p, c) {
      return vanExtend_(p, c);
    }, {});
  }
  function vanExtend_(result, opt) {
    result = result || {};
    return Object.keys(opt).reduce(function(p, c) {
      // if its an object
      if (typeof opt[c] === "object") {
        p[c] = vanExtend_(p[c], opt[c]);
      } else {
        p[c] = opt[c];
      }
      return p;
    }, result);
  }
  function fixDef_ (value , defValue) {
    return typeof value === typeof undefined ? defValue : value;
  }
};
For more like this see Google Apps Scripts Snippets

Subpages