JavaScript Code executing twice outside of functions





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















I am developing a site locally using D3 JS. When I do anything outside of any function it is happening twice, no matter where it is within the code. Example:



console.log("2x");

Console output is:
2x
2x


However if the code is inside any of the functions it only prints once. I noticed that next to the logs there is two different locations for their origin



Console output
2x site.js:3
2x site.js?v=twO2e-dF40DXz0Jm_X753ZBfaW8vwQs0ht7UrLyed5E:3


Inside a function the logs only originate from the longer string version. This affects any code outside a function, it seems to run twice...I've included the full code for reference if required.



I have found many similarly titled or tagged questions but all of them were due to the logging occurring in a loop or otherwise, I couldn't find any where it happened in the base code.



EDIT: My code does have two console.logs but that results in 4 prints in that case sorry for being unclear on that.



JavaScript



//Azibuda

console.log("2x");

//Get the SVG element
var svg = d3.select("svg");

var width = 960, height = 600;
var color = d3.scaleOrdinal(d3.schemeCategory20);

var link = svg.append("g").selectAll(".link");
var node = svg.append("g").selectAll(".node");
var label = svg.append("g").selectAll(".label");

//Begin the force simulation
var simulation = d3.forceSimulation()
.force("link", d3.forceLink().id(function (d) { return d.id; }).distance(50).strength(0.3))
.force("charge", d3.forceManyBody().strength(-15))
.force("center", d3.forceCenter(width / 2, height / 2));

//Highlight variables
var highlight_color = "blue";
var tHighlight = 0.05;

var config;

var linkedByIndex = {};
var linksAsString = {};

//Get the data
d3.json("/../../data.json", function (data) {

config = data;
if (!localStorage.graph)
{
localStorage.graph = JSON.stringify(data);
}
update();

});

function update() {

console.log(localStorage.graph);

//Create an array of source,target containing all links
config.links.forEach(function (d) {
linkedByIndex[d.source + "," + d.target] = true;
linkedByIndex[d.target + "," + d.source] = true;

//linksAsString[d.index] = d.source + "," + d.target;
});

var nodesAsString = {};
config.nodes.forEach(function (d) {
nodesAsString[d.index] = d.id + "," + d.radius;
});

//Draw links
link = link.data(config.links);
link.exit().remove();
link = link.enter().append("line")
.attr("class", "link")
.attr("stroke-width", 2)
.attr("stroke", "#888")
//.attr("opacity", function (d) { if (d.target.radius > 7) { return 1 }; return 0; })
.merge(link);


node = node.data(config.nodes);
node.exit().remove();
node = node.enter().append("circle")
.attr("class", "node")
.attr("r", function(d) { return d.radius; })
.attr("fill", function (d) { return color(d.id); })
.attr("stroke", "black")
// .attr("pointer-events", function (d) { if (d.radius <= 7) { return "none"; } return "visibleAll"; })
// .attr("opacity", function (d) { if (d.radius <= 7) { return 0; } return 1; })
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended))
.on("mouseover", mouseOver)
.on("mouseout", mouseOut)
.merge(node);

label = label.data(config.nodes);
label.exit().remove();
label = label.enter().append("text")
.attr("class", "label")
.attr("dx", function (d) { return d.radius * 1.25; })
.attr("dy", ".35em")
.attr("opacity", function (d) { if (d.radius <= 7) { return 0; } return 1; })
.attr("font-weight", "normal")
.style("font-size", 10)
.text(function (d) { return d.id; })
.merge(label);

//Add nodes to simulation
simulation
.nodes(config.nodes)
.on("tick", ticked);

//Add links to simulation
simulation.force("link")
.links(config.links);

simulation.alphaTarget(0.3).restart();
}

//Animating by ticks function
function ticked() {
node
.attr("cx", function (d) { return d.x = Math.max(d.radius, Math.min(width - d.radius, d.x)); })
.attr("cy", function (d) { return d.y = Math.max(d.radius, Math.min(height - d.radius, d.y)); });
link
.attr("x1", function (d) { return d.source.x; })
.attr("y1", function (d) { return d.source.y; })
.attr("x2", function (d) { return d.target.x; })
.attr("y2", function (d) { return d.target.y; });
label
.attr("x", function (d) { return d.x = Math.max(d.radius, Math.min(width - d.radius, d.x)); })
.attr("y", function (d) { return d.y = Math.max(d.radius, Math.min(height - d.radius, d.y)); });
}

//Using above array, check if two nodes are linked
function isConnected(node1, node2) {
return linkedByIndex[node1.id + "," + node2.id] || node1.index == node2.index;
}


//Highlight a node
function setHighlight(d) {
svg.style("cursor", "pointer");

//Set highlighted stroke around the current node, text and its links
node.style("stroke", function (tNode) {
return isConnected(d, tNode) ? highlight_color : "black";
});

label.style("font-weight", function (tNode) {
return isConnected(d, tNode) ? "bold" : "normal";
});

link.style("stroke", function (tNode) {
return tNode.source.index == d.index || tNode.target.index == d.index ? highlight_color : "#888";
});
}

//Drag/mousedown on a node
function dragstarted(d) {
if (!d3.event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}

//Dragging a node
function dragged(d) {
d.fx = d3.event.x;
d.fy = d3.event.y;

//Highlight/focus on held down node
setFocus(d);
setHighlight(d);
}

//End drag/mouseup on a node
function dragended(d) {
if (!d3.event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}

//Mouse over on a node
function mouseOver(d) {
setFocus(d);
setHighlight(d);
}

//Mouse off of a node
function mouseOut(d) {
unFocus(d);
highlightOff();
}

//Turning off highlight
function highlightOff() {
svg.style("cursor", "default");

//Set node attributes back to normal
node.style("stroke", "black");
label.style("font-weight", "normal");
link.style("stroke", "#888");
}

//Focus on a node
function setFocus(d) {
//Set opacity of all non-connected nodes and their elements (text/links) to faded
node.style("opacity", function (tNode) {
return isConnected(d, tNode) ? 1 : tHighlight;
});

label.style("opacity", function (tNode) {
return isConnected(d, tNode) ? 1 : tHighlight;
});

link.style("opacity", function (tNode) {
return tNode.source.index == d.index || tNode.target.index == d.index ? 1 : tHighlight;
});
}

//Unfocus on a node (reset all to normal)
function unFocus(d) {
//node.style("opacity", function (d) { if (d.radius <= 7) { return 0; } return 1; });
//node.style("pointer-events", function (d) { if (d.radius <= 7) { return "none"; } return "visibleAll"; })
node.style("opacity", 1);
label.style("opacity", function (d) { if (d.radius <= 7) { return 0; } return 1; });
//link.style("opacity", function (d) { if (d.target.radius > 7) { return 1 }; return 0; });
link.style("opacity", 1);
}

function updateR()
{
console.log(config.nodes[2]);
config.nodes.splice(2, 1);
update();
}

var temp = JSON.parse(localStorage.graph);

//temp.nodes.push({"id":"Cheese", "radius":20});

//localStorage.graph = JSON.stringify(temp);

console.log("2x");


HTML



@{
ViewData["Title"] = "Home Page";
}
<link href="/css/geico-design-kit.css" rel="stylesheet">
<script src="~/js/geico-design-kit.bundle.js"></script>
<script src="~/js/d3.js"></script>
<script src="~/js/site.js"></script>
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
.link line {
stroke: #888;
}

text {
pointer-events: none;
font: 10px sans-serif;
}
</style>


<div class="col-md-12">
<div class="col-md-3">
<h2>Quick Links</h2>
<ul class="list list--unordered">
<li>Example Quick Links Here</li>
<li><a href="http://www.google.com">Google</a></li>
<li><a href="http://www.google.com">Google</a></li>
</ul>
</div>
</div>
<button onclick="updateR()" type="button" style="background-color:red">DO NOT PRESS!</button>

<svg id="container" width="960" height="600" style="border:1px solid black;"></svg>
<form id="nodes"></form>









share|improve this question




















  • 1





    The code you posted has two console.log("2x");. One at the top, and one at the bottom.

    – Mark Meyer
    Nov 16 '18 at 19:26













  • Yes, this results in 4 prints, sorry for not being clear on that, I was testing it placing in multiple areas.

    – A Zibuda
    Nov 16 '18 at 19:35






  • 1





    I can't reproduce this — your code is just giving me to 2x logs. The urls suggests that perhaps there is something redirecting the page from site.js to site.js?v=foo. Do you see something like that going on the browser's developer tools?

    – Mark Meyer
    Nov 16 '18 at 19:46











  • Can you record you network your network log and see if your browser is making 2 instead of 1? It would be the red button under the Network tab in chrome dev tools.

    – Tom O.
    Nov 16 '18 at 19:48











  • Yes that is happening based on the logs and it's also showing it loading in the network section of the Chrome console, but I have no idea why there is a second file being loaded/run or where it's coming from.

    – A Zibuda
    Nov 16 '18 at 19:49


















0















I am developing a site locally using D3 JS. When I do anything outside of any function it is happening twice, no matter where it is within the code. Example:



console.log("2x");

Console output is:
2x
2x


However if the code is inside any of the functions it only prints once. I noticed that next to the logs there is two different locations for their origin



Console output
2x site.js:3
2x site.js?v=twO2e-dF40DXz0Jm_X753ZBfaW8vwQs0ht7UrLyed5E:3


Inside a function the logs only originate from the longer string version. This affects any code outside a function, it seems to run twice...I've included the full code for reference if required.



I have found many similarly titled or tagged questions but all of them were due to the logging occurring in a loop or otherwise, I couldn't find any where it happened in the base code.



EDIT: My code does have two console.logs but that results in 4 prints in that case sorry for being unclear on that.



JavaScript



//Azibuda

console.log("2x");

//Get the SVG element
var svg = d3.select("svg");

var width = 960, height = 600;
var color = d3.scaleOrdinal(d3.schemeCategory20);

var link = svg.append("g").selectAll(".link");
var node = svg.append("g").selectAll(".node");
var label = svg.append("g").selectAll(".label");

//Begin the force simulation
var simulation = d3.forceSimulation()
.force("link", d3.forceLink().id(function (d) { return d.id; }).distance(50).strength(0.3))
.force("charge", d3.forceManyBody().strength(-15))
.force("center", d3.forceCenter(width / 2, height / 2));

//Highlight variables
var highlight_color = "blue";
var tHighlight = 0.05;

var config;

var linkedByIndex = {};
var linksAsString = {};

//Get the data
d3.json("/../../data.json", function (data) {

config = data;
if (!localStorage.graph)
{
localStorage.graph = JSON.stringify(data);
}
update();

});

function update() {

console.log(localStorage.graph);

//Create an array of source,target containing all links
config.links.forEach(function (d) {
linkedByIndex[d.source + "," + d.target] = true;
linkedByIndex[d.target + "," + d.source] = true;

//linksAsString[d.index] = d.source + "," + d.target;
});

var nodesAsString = {};
config.nodes.forEach(function (d) {
nodesAsString[d.index] = d.id + "," + d.radius;
});

//Draw links
link = link.data(config.links);
link.exit().remove();
link = link.enter().append("line")
.attr("class", "link")
.attr("stroke-width", 2)
.attr("stroke", "#888")
//.attr("opacity", function (d) { if (d.target.radius > 7) { return 1 }; return 0; })
.merge(link);


node = node.data(config.nodes);
node.exit().remove();
node = node.enter().append("circle")
.attr("class", "node")
.attr("r", function(d) { return d.radius; })
.attr("fill", function (d) { return color(d.id); })
.attr("stroke", "black")
// .attr("pointer-events", function (d) { if (d.radius <= 7) { return "none"; } return "visibleAll"; })
// .attr("opacity", function (d) { if (d.radius <= 7) { return 0; } return 1; })
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended))
.on("mouseover", mouseOver)
.on("mouseout", mouseOut)
.merge(node);

label = label.data(config.nodes);
label.exit().remove();
label = label.enter().append("text")
.attr("class", "label")
.attr("dx", function (d) { return d.radius * 1.25; })
.attr("dy", ".35em")
.attr("opacity", function (d) { if (d.radius <= 7) { return 0; } return 1; })
.attr("font-weight", "normal")
.style("font-size", 10)
.text(function (d) { return d.id; })
.merge(label);

//Add nodes to simulation
simulation
.nodes(config.nodes)
.on("tick", ticked);

//Add links to simulation
simulation.force("link")
.links(config.links);

simulation.alphaTarget(0.3).restart();
}

//Animating by ticks function
function ticked() {
node
.attr("cx", function (d) { return d.x = Math.max(d.radius, Math.min(width - d.radius, d.x)); })
.attr("cy", function (d) { return d.y = Math.max(d.radius, Math.min(height - d.radius, d.y)); });
link
.attr("x1", function (d) { return d.source.x; })
.attr("y1", function (d) { return d.source.y; })
.attr("x2", function (d) { return d.target.x; })
.attr("y2", function (d) { return d.target.y; });
label
.attr("x", function (d) { return d.x = Math.max(d.radius, Math.min(width - d.radius, d.x)); })
.attr("y", function (d) { return d.y = Math.max(d.radius, Math.min(height - d.radius, d.y)); });
}

//Using above array, check if two nodes are linked
function isConnected(node1, node2) {
return linkedByIndex[node1.id + "," + node2.id] || node1.index == node2.index;
}


//Highlight a node
function setHighlight(d) {
svg.style("cursor", "pointer");

//Set highlighted stroke around the current node, text and its links
node.style("stroke", function (tNode) {
return isConnected(d, tNode) ? highlight_color : "black";
});

label.style("font-weight", function (tNode) {
return isConnected(d, tNode) ? "bold" : "normal";
});

link.style("stroke", function (tNode) {
return tNode.source.index == d.index || tNode.target.index == d.index ? highlight_color : "#888";
});
}

//Drag/mousedown on a node
function dragstarted(d) {
if (!d3.event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}

//Dragging a node
function dragged(d) {
d.fx = d3.event.x;
d.fy = d3.event.y;

//Highlight/focus on held down node
setFocus(d);
setHighlight(d);
}

//End drag/mouseup on a node
function dragended(d) {
if (!d3.event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}

//Mouse over on a node
function mouseOver(d) {
setFocus(d);
setHighlight(d);
}

//Mouse off of a node
function mouseOut(d) {
unFocus(d);
highlightOff();
}

//Turning off highlight
function highlightOff() {
svg.style("cursor", "default");

//Set node attributes back to normal
node.style("stroke", "black");
label.style("font-weight", "normal");
link.style("stroke", "#888");
}

//Focus on a node
function setFocus(d) {
//Set opacity of all non-connected nodes and their elements (text/links) to faded
node.style("opacity", function (tNode) {
return isConnected(d, tNode) ? 1 : tHighlight;
});

label.style("opacity", function (tNode) {
return isConnected(d, tNode) ? 1 : tHighlight;
});

link.style("opacity", function (tNode) {
return tNode.source.index == d.index || tNode.target.index == d.index ? 1 : tHighlight;
});
}

//Unfocus on a node (reset all to normal)
function unFocus(d) {
//node.style("opacity", function (d) { if (d.radius <= 7) { return 0; } return 1; });
//node.style("pointer-events", function (d) { if (d.radius <= 7) { return "none"; } return "visibleAll"; })
node.style("opacity", 1);
label.style("opacity", function (d) { if (d.radius <= 7) { return 0; } return 1; });
//link.style("opacity", function (d) { if (d.target.radius > 7) { return 1 }; return 0; });
link.style("opacity", 1);
}

function updateR()
{
console.log(config.nodes[2]);
config.nodes.splice(2, 1);
update();
}

var temp = JSON.parse(localStorage.graph);

//temp.nodes.push({"id":"Cheese", "radius":20});

//localStorage.graph = JSON.stringify(temp);

console.log("2x");


HTML



@{
ViewData["Title"] = "Home Page";
}
<link href="/css/geico-design-kit.css" rel="stylesheet">
<script src="~/js/geico-design-kit.bundle.js"></script>
<script src="~/js/d3.js"></script>
<script src="~/js/site.js"></script>
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
.link line {
stroke: #888;
}

text {
pointer-events: none;
font: 10px sans-serif;
}
</style>


<div class="col-md-12">
<div class="col-md-3">
<h2>Quick Links</h2>
<ul class="list list--unordered">
<li>Example Quick Links Here</li>
<li><a href="http://www.google.com">Google</a></li>
<li><a href="http://www.google.com">Google</a></li>
</ul>
</div>
</div>
<button onclick="updateR()" type="button" style="background-color:red">DO NOT PRESS!</button>

<svg id="container" width="960" height="600" style="border:1px solid black;"></svg>
<form id="nodes"></form>









share|improve this question




















  • 1





    The code you posted has two console.log("2x");. One at the top, and one at the bottom.

    – Mark Meyer
    Nov 16 '18 at 19:26













  • Yes, this results in 4 prints, sorry for not being clear on that, I was testing it placing in multiple areas.

    – A Zibuda
    Nov 16 '18 at 19:35






  • 1





    I can't reproduce this — your code is just giving me to 2x logs. The urls suggests that perhaps there is something redirecting the page from site.js to site.js?v=foo. Do you see something like that going on the browser's developer tools?

    – Mark Meyer
    Nov 16 '18 at 19:46











  • Can you record you network your network log and see if your browser is making 2 instead of 1? It would be the red button under the Network tab in chrome dev tools.

    – Tom O.
    Nov 16 '18 at 19:48











  • Yes that is happening based on the logs and it's also showing it loading in the network section of the Chrome console, but I have no idea why there is a second file being loaded/run or where it's coming from.

    – A Zibuda
    Nov 16 '18 at 19:49














0












0








0








I am developing a site locally using D3 JS. When I do anything outside of any function it is happening twice, no matter where it is within the code. Example:



console.log("2x");

Console output is:
2x
2x


However if the code is inside any of the functions it only prints once. I noticed that next to the logs there is two different locations for their origin



Console output
2x site.js:3
2x site.js?v=twO2e-dF40DXz0Jm_X753ZBfaW8vwQs0ht7UrLyed5E:3


Inside a function the logs only originate from the longer string version. This affects any code outside a function, it seems to run twice...I've included the full code for reference if required.



I have found many similarly titled or tagged questions but all of them were due to the logging occurring in a loop or otherwise, I couldn't find any where it happened in the base code.



EDIT: My code does have two console.logs but that results in 4 prints in that case sorry for being unclear on that.



JavaScript



//Azibuda

console.log("2x");

//Get the SVG element
var svg = d3.select("svg");

var width = 960, height = 600;
var color = d3.scaleOrdinal(d3.schemeCategory20);

var link = svg.append("g").selectAll(".link");
var node = svg.append("g").selectAll(".node");
var label = svg.append("g").selectAll(".label");

//Begin the force simulation
var simulation = d3.forceSimulation()
.force("link", d3.forceLink().id(function (d) { return d.id; }).distance(50).strength(0.3))
.force("charge", d3.forceManyBody().strength(-15))
.force("center", d3.forceCenter(width / 2, height / 2));

//Highlight variables
var highlight_color = "blue";
var tHighlight = 0.05;

var config;

var linkedByIndex = {};
var linksAsString = {};

//Get the data
d3.json("/../../data.json", function (data) {

config = data;
if (!localStorage.graph)
{
localStorage.graph = JSON.stringify(data);
}
update();

});

function update() {

console.log(localStorage.graph);

//Create an array of source,target containing all links
config.links.forEach(function (d) {
linkedByIndex[d.source + "," + d.target] = true;
linkedByIndex[d.target + "," + d.source] = true;

//linksAsString[d.index] = d.source + "," + d.target;
});

var nodesAsString = {};
config.nodes.forEach(function (d) {
nodesAsString[d.index] = d.id + "," + d.radius;
});

//Draw links
link = link.data(config.links);
link.exit().remove();
link = link.enter().append("line")
.attr("class", "link")
.attr("stroke-width", 2)
.attr("stroke", "#888")
//.attr("opacity", function (d) { if (d.target.radius > 7) { return 1 }; return 0; })
.merge(link);


node = node.data(config.nodes);
node.exit().remove();
node = node.enter().append("circle")
.attr("class", "node")
.attr("r", function(d) { return d.radius; })
.attr("fill", function (d) { return color(d.id); })
.attr("stroke", "black")
// .attr("pointer-events", function (d) { if (d.radius <= 7) { return "none"; } return "visibleAll"; })
// .attr("opacity", function (d) { if (d.radius <= 7) { return 0; } return 1; })
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended))
.on("mouseover", mouseOver)
.on("mouseout", mouseOut)
.merge(node);

label = label.data(config.nodes);
label.exit().remove();
label = label.enter().append("text")
.attr("class", "label")
.attr("dx", function (d) { return d.radius * 1.25; })
.attr("dy", ".35em")
.attr("opacity", function (d) { if (d.radius <= 7) { return 0; } return 1; })
.attr("font-weight", "normal")
.style("font-size", 10)
.text(function (d) { return d.id; })
.merge(label);

//Add nodes to simulation
simulation
.nodes(config.nodes)
.on("tick", ticked);

//Add links to simulation
simulation.force("link")
.links(config.links);

simulation.alphaTarget(0.3).restart();
}

//Animating by ticks function
function ticked() {
node
.attr("cx", function (d) { return d.x = Math.max(d.radius, Math.min(width - d.radius, d.x)); })
.attr("cy", function (d) { return d.y = Math.max(d.radius, Math.min(height - d.radius, d.y)); });
link
.attr("x1", function (d) { return d.source.x; })
.attr("y1", function (d) { return d.source.y; })
.attr("x2", function (d) { return d.target.x; })
.attr("y2", function (d) { return d.target.y; });
label
.attr("x", function (d) { return d.x = Math.max(d.radius, Math.min(width - d.radius, d.x)); })
.attr("y", function (d) { return d.y = Math.max(d.radius, Math.min(height - d.radius, d.y)); });
}

//Using above array, check if two nodes are linked
function isConnected(node1, node2) {
return linkedByIndex[node1.id + "," + node2.id] || node1.index == node2.index;
}


//Highlight a node
function setHighlight(d) {
svg.style("cursor", "pointer");

//Set highlighted stroke around the current node, text and its links
node.style("stroke", function (tNode) {
return isConnected(d, tNode) ? highlight_color : "black";
});

label.style("font-weight", function (tNode) {
return isConnected(d, tNode) ? "bold" : "normal";
});

link.style("stroke", function (tNode) {
return tNode.source.index == d.index || tNode.target.index == d.index ? highlight_color : "#888";
});
}

//Drag/mousedown on a node
function dragstarted(d) {
if (!d3.event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}

//Dragging a node
function dragged(d) {
d.fx = d3.event.x;
d.fy = d3.event.y;

//Highlight/focus on held down node
setFocus(d);
setHighlight(d);
}

//End drag/mouseup on a node
function dragended(d) {
if (!d3.event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}

//Mouse over on a node
function mouseOver(d) {
setFocus(d);
setHighlight(d);
}

//Mouse off of a node
function mouseOut(d) {
unFocus(d);
highlightOff();
}

//Turning off highlight
function highlightOff() {
svg.style("cursor", "default");

//Set node attributes back to normal
node.style("stroke", "black");
label.style("font-weight", "normal");
link.style("stroke", "#888");
}

//Focus on a node
function setFocus(d) {
//Set opacity of all non-connected nodes and their elements (text/links) to faded
node.style("opacity", function (tNode) {
return isConnected(d, tNode) ? 1 : tHighlight;
});

label.style("opacity", function (tNode) {
return isConnected(d, tNode) ? 1 : tHighlight;
});

link.style("opacity", function (tNode) {
return tNode.source.index == d.index || tNode.target.index == d.index ? 1 : tHighlight;
});
}

//Unfocus on a node (reset all to normal)
function unFocus(d) {
//node.style("opacity", function (d) { if (d.radius <= 7) { return 0; } return 1; });
//node.style("pointer-events", function (d) { if (d.radius <= 7) { return "none"; } return "visibleAll"; })
node.style("opacity", 1);
label.style("opacity", function (d) { if (d.radius <= 7) { return 0; } return 1; });
//link.style("opacity", function (d) { if (d.target.radius > 7) { return 1 }; return 0; });
link.style("opacity", 1);
}

function updateR()
{
console.log(config.nodes[2]);
config.nodes.splice(2, 1);
update();
}

var temp = JSON.parse(localStorage.graph);

//temp.nodes.push({"id":"Cheese", "radius":20});

//localStorage.graph = JSON.stringify(temp);

console.log("2x");


HTML



@{
ViewData["Title"] = "Home Page";
}
<link href="/css/geico-design-kit.css" rel="stylesheet">
<script src="~/js/geico-design-kit.bundle.js"></script>
<script src="~/js/d3.js"></script>
<script src="~/js/site.js"></script>
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
.link line {
stroke: #888;
}

text {
pointer-events: none;
font: 10px sans-serif;
}
</style>


<div class="col-md-12">
<div class="col-md-3">
<h2>Quick Links</h2>
<ul class="list list--unordered">
<li>Example Quick Links Here</li>
<li><a href="http://www.google.com">Google</a></li>
<li><a href="http://www.google.com">Google</a></li>
</ul>
</div>
</div>
<button onclick="updateR()" type="button" style="background-color:red">DO NOT PRESS!</button>

<svg id="container" width="960" height="600" style="border:1px solid black;"></svg>
<form id="nodes"></form>









share|improve this question
















I am developing a site locally using D3 JS. When I do anything outside of any function it is happening twice, no matter where it is within the code. Example:



console.log("2x");

Console output is:
2x
2x


However if the code is inside any of the functions it only prints once. I noticed that next to the logs there is two different locations for their origin



Console output
2x site.js:3
2x site.js?v=twO2e-dF40DXz0Jm_X753ZBfaW8vwQs0ht7UrLyed5E:3


Inside a function the logs only originate from the longer string version. This affects any code outside a function, it seems to run twice...I've included the full code for reference if required.



I have found many similarly titled or tagged questions but all of them were due to the logging occurring in a loop or otherwise, I couldn't find any where it happened in the base code.



EDIT: My code does have two console.logs but that results in 4 prints in that case sorry for being unclear on that.



JavaScript



//Azibuda

console.log("2x");

//Get the SVG element
var svg = d3.select("svg");

var width = 960, height = 600;
var color = d3.scaleOrdinal(d3.schemeCategory20);

var link = svg.append("g").selectAll(".link");
var node = svg.append("g").selectAll(".node");
var label = svg.append("g").selectAll(".label");

//Begin the force simulation
var simulation = d3.forceSimulation()
.force("link", d3.forceLink().id(function (d) { return d.id; }).distance(50).strength(0.3))
.force("charge", d3.forceManyBody().strength(-15))
.force("center", d3.forceCenter(width / 2, height / 2));

//Highlight variables
var highlight_color = "blue";
var tHighlight = 0.05;

var config;

var linkedByIndex = {};
var linksAsString = {};

//Get the data
d3.json("/../../data.json", function (data) {

config = data;
if (!localStorage.graph)
{
localStorage.graph = JSON.stringify(data);
}
update();

});

function update() {

console.log(localStorage.graph);

//Create an array of source,target containing all links
config.links.forEach(function (d) {
linkedByIndex[d.source + "," + d.target] = true;
linkedByIndex[d.target + "," + d.source] = true;

//linksAsString[d.index] = d.source + "," + d.target;
});

var nodesAsString = {};
config.nodes.forEach(function (d) {
nodesAsString[d.index] = d.id + "," + d.radius;
});

//Draw links
link = link.data(config.links);
link.exit().remove();
link = link.enter().append("line")
.attr("class", "link")
.attr("stroke-width", 2)
.attr("stroke", "#888")
//.attr("opacity", function (d) { if (d.target.radius > 7) { return 1 }; return 0; })
.merge(link);


node = node.data(config.nodes);
node.exit().remove();
node = node.enter().append("circle")
.attr("class", "node")
.attr("r", function(d) { return d.radius; })
.attr("fill", function (d) { return color(d.id); })
.attr("stroke", "black")
// .attr("pointer-events", function (d) { if (d.radius <= 7) { return "none"; } return "visibleAll"; })
// .attr("opacity", function (d) { if (d.radius <= 7) { return 0; } return 1; })
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended))
.on("mouseover", mouseOver)
.on("mouseout", mouseOut)
.merge(node);

label = label.data(config.nodes);
label.exit().remove();
label = label.enter().append("text")
.attr("class", "label")
.attr("dx", function (d) { return d.radius * 1.25; })
.attr("dy", ".35em")
.attr("opacity", function (d) { if (d.radius <= 7) { return 0; } return 1; })
.attr("font-weight", "normal")
.style("font-size", 10)
.text(function (d) { return d.id; })
.merge(label);

//Add nodes to simulation
simulation
.nodes(config.nodes)
.on("tick", ticked);

//Add links to simulation
simulation.force("link")
.links(config.links);

simulation.alphaTarget(0.3).restart();
}

//Animating by ticks function
function ticked() {
node
.attr("cx", function (d) { return d.x = Math.max(d.radius, Math.min(width - d.radius, d.x)); })
.attr("cy", function (d) { return d.y = Math.max(d.radius, Math.min(height - d.radius, d.y)); });
link
.attr("x1", function (d) { return d.source.x; })
.attr("y1", function (d) { return d.source.y; })
.attr("x2", function (d) { return d.target.x; })
.attr("y2", function (d) { return d.target.y; });
label
.attr("x", function (d) { return d.x = Math.max(d.radius, Math.min(width - d.radius, d.x)); })
.attr("y", function (d) { return d.y = Math.max(d.radius, Math.min(height - d.radius, d.y)); });
}

//Using above array, check if two nodes are linked
function isConnected(node1, node2) {
return linkedByIndex[node1.id + "," + node2.id] || node1.index == node2.index;
}


//Highlight a node
function setHighlight(d) {
svg.style("cursor", "pointer");

//Set highlighted stroke around the current node, text and its links
node.style("stroke", function (tNode) {
return isConnected(d, tNode) ? highlight_color : "black";
});

label.style("font-weight", function (tNode) {
return isConnected(d, tNode) ? "bold" : "normal";
});

link.style("stroke", function (tNode) {
return tNode.source.index == d.index || tNode.target.index == d.index ? highlight_color : "#888";
});
}

//Drag/mousedown on a node
function dragstarted(d) {
if (!d3.event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}

//Dragging a node
function dragged(d) {
d.fx = d3.event.x;
d.fy = d3.event.y;

//Highlight/focus on held down node
setFocus(d);
setHighlight(d);
}

//End drag/mouseup on a node
function dragended(d) {
if (!d3.event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}

//Mouse over on a node
function mouseOver(d) {
setFocus(d);
setHighlight(d);
}

//Mouse off of a node
function mouseOut(d) {
unFocus(d);
highlightOff();
}

//Turning off highlight
function highlightOff() {
svg.style("cursor", "default");

//Set node attributes back to normal
node.style("stroke", "black");
label.style("font-weight", "normal");
link.style("stroke", "#888");
}

//Focus on a node
function setFocus(d) {
//Set opacity of all non-connected nodes and their elements (text/links) to faded
node.style("opacity", function (tNode) {
return isConnected(d, tNode) ? 1 : tHighlight;
});

label.style("opacity", function (tNode) {
return isConnected(d, tNode) ? 1 : tHighlight;
});

link.style("opacity", function (tNode) {
return tNode.source.index == d.index || tNode.target.index == d.index ? 1 : tHighlight;
});
}

//Unfocus on a node (reset all to normal)
function unFocus(d) {
//node.style("opacity", function (d) { if (d.radius <= 7) { return 0; } return 1; });
//node.style("pointer-events", function (d) { if (d.radius <= 7) { return "none"; } return "visibleAll"; })
node.style("opacity", 1);
label.style("opacity", function (d) { if (d.radius <= 7) { return 0; } return 1; });
//link.style("opacity", function (d) { if (d.target.radius > 7) { return 1 }; return 0; });
link.style("opacity", 1);
}

function updateR()
{
console.log(config.nodes[2]);
config.nodes.splice(2, 1);
update();
}

var temp = JSON.parse(localStorage.graph);

//temp.nodes.push({"id":"Cheese", "radius":20});

//localStorage.graph = JSON.stringify(temp);

console.log("2x");


HTML



@{
ViewData["Title"] = "Home Page";
}
<link href="/css/geico-design-kit.css" rel="stylesheet">
<script src="~/js/geico-design-kit.bundle.js"></script>
<script src="~/js/d3.js"></script>
<script src="~/js/site.js"></script>
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
.link line {
stroke: #888;
}

text {
pointer-events: none;
font: 10px sans-serif;
}
</style>


<div class="col-md-12">
<div class="col-md-3">
<h2>Quick Links</h2>
<ul class="list list--unordered">
<li>Example Quick Links Here</li>
<li><a href="http://www.google.com">Google</a></li>
<li><a href="http://www.google.com">Google</a></li>
</ul>
</div>
</div>
<button onclick="updateR()" type="button" style="background-color:red">DO NOT PRESS!</button>

<svg id="container" width="960" height="600" style="border:1px solid black;"></svg>
<form id="nodes"></form>






javascript html google-chrome d3.js






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 16 '18 at 19:35







A Zibuda

















asked Nov 16 '18 at 19:23









A ZibudaA Zibuda

388




388








  • 1





    The code you posted has two console.log("2x");. One at the top, and one at the bottom.

    – Mark Meyer
    Nov 16 '18 at 19:26













  • Yes, this results in 4 prints, sorry for not being clear on that, I was testing it placing in multiple areas.

    – A Zibuda
    Nov 16 '18 at 19:35






  • 1





    I can't reproduce this — your code is just giving me to 2x logs. The urls suggests that perhaps there is something redirecting the page from site.js to site.js?v=foo. Do you see something like that going on the browser's developer tools?

    – Mark Meyer
    Nov 16 '18 at 19:46











  • Can you record you network your network log and see if your browser is making 2 instead of 1? It would be the red button under the Network tab in chrome dev tools.

    – Tom O.
    Nov 16 '18 at 19:48











  • Yes that is happening based on the logs and it's also showing it loading in the network section of the Chrome console, but I have no idea why there is a second file being loaded/run or where it's coming from.

    – A Zibuda
    Nov 16 '18 at 19:49














  • 1





    The code you posted has two console.log("2x");. One at the top, and one at the bottom.

    – Mark Meyer
    Nov 16 '18 at 19:26













  • Yes, this results in 4 prints, sorry for not being clear on that, I was testing it placing in multiple areas.

    – A Zibuda
    Nov 16 '18 at 19:35






  • 1





    I can't reproduce this — your code is just giving me to 2x logs. The urls suggests that perhaps there is something redirecting the page from site.js to site.js?v=foo. Do you see something like that going on the browser's developer tools?

    – Mark Meyer
    Nov 16 '18 at 19:46











  • Can you record you network your network log and see if your browser is making 2 instead of 1? It would be the red button under the Network tab in chrome dev tools.

    – Tom O.
    Nov 16 '18 at 19:48











  • Yes that is happening based on the logs and it's also showing it loading in the network section of the Chrome console, but I have no idea why there is a second file being loaded/run or where it's coming from.

    – A Zibuda
    Nov 16 '18 at 19:49








1




1





The code you posted has two console.log("2x");. One at the top, and one at the bottom.

– Mark Meyer
Nov 16 '18 at 19:26







The code you posted has two console.log("2x");. One at the top, and one at the bottom.

– Mark Meyer
Nov 16 '18 at 19:26















Yes, this results in 4 prints, sorry for not being clear on that, I was testing it placing in multiple areas.

– A Zibuda
Nov 16 '18 at 19:35





Yes, this results in 4 prints, sorry for not being clear on that, I was testing it placing in multiple areas.

– A Zibuda
Nov 16 '18 at 19:35




1




1





I can't reproduce this — your code is just giving me to 2x logs. The urls suggests that perhaps there is something redirecting the page from site.js to site.js?v=foo. Do you see something like that going on the browser's developer tools?

– Mark Meyer
Nov 16 '18 at 19:46





I can't reproduce this — your code is just giving me to 2x logs. The urls suggests that perhaps there is something redirecting the page from site.js to site.js?v=foo. Do you see something like that going on the browser's developer tools?

– Mark Meyer
Nov 16 '18 at 19:46













Can you record you network your network log and see if your browser is making 2 instead of 1? It would be the red button under the Network tab in chrome dev tools.

– Tom O.
Nov 16 '18 at 19:48





Can you record you network your network log and see if your browser is making 2 instead of 1? It would be the red button under the Network tab in chrome dev tools.

– Tom O.
Nov 16 '18 at 19:48













Yes that is happening based on the logs and it's also showing it loading in the network section of the Chrome console, but I have no idea why there is a second file being loaded/run or where it's coming from.

– A Zibuda
Nov 16 '18 at 19:49





Yes that is happening based on the logs and it's also showing it loading in the network section of the Chrome console, but I have no idea why there is a second file being loaded/run or where it's coming from.

– A Zibuda
Nov 16 '18 at 19:49












1 Answer
1






active

oldest

votes


















0














If this ASP.NET view is using a layout view and the same file is referenced in that layout file, the rendered output would have multiple references.






share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53344163%2fjavascript-code-executing-twice-outside-of-functions%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    If this ASP.NET view is using a layout view and the same file is referenced in that layout file, the rendered output would have multiple references.






    share|improve this answer




























      0














      If this ASP.NET view is using a layout view and the same file is referenced in that layout file, the rendered output would have multiple references.






      share|improve this answer


























        0












        0








        0







        If this ASP.NET view is using a layout view and the same file is referenced in that layout file, the rendered output would have multiple references.






        share|improve this answer













        If this ASP.NET view is using a layout view and the same file is referenced in that layout file, the rendered output would have multiple references.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 16 '18 at 20:21









        Charmis VargheseCharmis Varghese

        906




        906
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53344163%2fjavascript-code-executing-twice-outside-of-functions%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown