javascriptwhile-looponmousedownonmouseup

while onmousedown javascript


I'm working on a world map and trying to change from green to red, the color of the country that is being clicked on while holding down the mouse. I'm able to change the color with multiple clicks but when i tried to add the while loop it just froze. Can you help me out please ? also how can I keep the color looping from green to red ? meaning once it reaches the color red and I keep holing down the mouse, it changes to green and etc... Heres a fiddle for it

var color = d3.scale.linear().domain([0, 50]).range(["green", "red"]);
var pas = [];
var ismousedown = -1;

country
    .on("mousemove", function(d, i) {

        var mouse = d3.mouse(svg.node()).map(function(d) {
            return parseInt(d);
        });

        tooltip.classed("hidden", false)
            .attr("style", "left:" + (mouse[0] + offsetL) + "px;top:" + (mouse[1] + offsetT) + "px")
            .html(d.properties.name);

    })
    .on("mouseout", function(d, i) {
        tooltip.classed("hidden", true);
    })
    .on("mouseup", function(d, i) {
        ismousedown = 0;
    })
    .on("mouseout", function(d, i) {
        tooltip.classed("hidden", true);
    })
    .on("mousedown", function(d, i) {
        ismousedown = 1;
        while (ismousedown == 1) {
            if (pas[d.id]) {
                pas[d.id]++;
            } else {
                pas[d.id] = 1;
            }

            d3.select(this)
                .classed("active", false)
                .style("fill", function(d, i) {
                    return color(pas[d.id]);
                    return d.properties.color;
                });
        }
    });

Solution

  • I modified your solution to use setInterval(). This will automatically run a function every N number of milliseconds. In this example, while the mouse is down, the color updating code will run every 10ms (you can adjust this in the mousedown function). When the mouse is released, the interval is cleared so it no longer runs.

    Updated JSFiddle (note: I also added some variables to the top of the function)

    .on("mousedown", function(d,i) {
      var that = this;
      ismousedown = true;
    
      colorInterval = window.setInterval(function () {
        // ...
      }, 10); // <== runs every 10 milliseconds
    })
    
    .on("mouseup", function(d,i) {
      window.clearInterval(colorInterval);
    });