Skip to content Skip to sidebar Skip to footer

How Frequently Is D3 Drag Event Triggered?

I have a very general low level question about dragging. I am specifically interested in learning what exactly determines when a drag event is triggered in D3.js v4. For example, i

Solution 1:

The issue you're seeing has little to do with D3, it's a general JavaScript behaviour or, better yet, a browser-related behaviour: what you're seeing is a feature of mousemove.

If you look at the D3 API, you'll see that the "drag" event uses mousemove (or touchmove for touch devices):

drag - after an active pointer moves (on mousemove or touchmove).

Now comes the important information: mousemove is generated by the browser. More important than that, the browser is not obligated to generate the event by any specific rate, be it related to distance or time. Also, other factors may influence the frequency of mousemove, as the hardware you're using for instance.

So, if we assume (just for simplification) that the browser generates a mousemove event every 100ms, you have a simple explanation for the behaviour you described:

Given that speed = distance / time, if you move your mouse faster, you'll have less events from point A to B (that is, the distance from a mousemove event to the next will be bigger). If you move your mouse slower, you'll have more events from point A to B (that is, the distance from a mousemove event to the next will be smaller). If you move your mouse in a speed less than 1px/100ms (in our hypothetical scenario), you'll have 1 event per pixel.

Finally, here is a very simple demo showing it. Click and drag anywhere in the SVG:

var count = 0;
d3.select("svg").call(d3.drag().on("start", function() {
  console.log("drag started")
}).on("drag", function() {
  ++count; 
  console.log("drag event " + count)
}).on("end", function() {
  count = 0;
  console.log("drag ended")
}))
.as-console-wrapper { max-height: 20%!important;}
svg {
  border: 1px solid black;
}
<scriptsrc="https://d3js.org/d3.v4.min.js"></script><svg></svg>

Post a Comment for "How Frequently Is D3 Drag Event Triggered?"