Search code examples
javascriptcytoscape.jscytoscape

Cytoscape : Add element in setTimeout doesn't get rendered


In the following code , I add a node to the graph in setTimout but it's not rendered. When I move the code out of setTimeout it's drawn. Any reason ?

var cytoscape = require('cytoscape');

var cy = cytoscape({
    container: document.getElementById('container'),
    layout: {
        name: 'circle'
    }
});

cy.add({
        group: "nodes",
        data: {
            id: 'id1'
        }
    }
); // this adding is drawn
console.log(cy.nodes()); // this shows that the node with id:id1 is added 

setTimeout(function() {
    cy.add({
            group: "nodes",
            data: {
                id: 'id2'
            }
        }
    ); // this one doesn't get drawn
    console.log(cy.nodes()); // BUT, this shows that the node with id:id2 is added 
}, 500);

Solution

  • You haven't defined a position, so the node can't render. Define the position of nodes explicitly or call layouts explicitly.

    Explanation: Assuming this is on init of the page, you've created a race condition: The graph can't render until DOMContentLoaded. So, the layout is delayed until after that event. You've created the situation where id1 is added before the layout and id2 is added after. So, id1 has a position and can be rendered, but id2 has no position and can't be rendered.

    In 2.4.8, nodes will have a default position of (0, 0) to make it easier to avoid mistakes like this.