Search code examples
javascriptdhtmlx

Javascript SetTimeOut on click doesn't respect the time delay after 2-3 clicks


I am writing a code in javascript dhtmlx. I have an onclick event on a grid. When i click the grid a window shows up which i want to be gone after 4 sec. i tried the setTimeOut but after 2-3 consecutive clicks it messes up with the time and hides the windows almost immediately. Here is the code:

 var dhxWindow = new dhx.Window({
                    modal: false,
                    header: false,
                    footer: false,
                    resizable: false,
                    css: "toolbar",
                    movable: false,
                    height: 130,
                    expire: 4000
                });

var toolbar = new dhx.Toolbar("toolbar_container", {

                });
grid.events.on("CellClick", function (row, column, e) {

                    var data = [
                        {
                            id: "data1",
                            type: "imageButton",


                        },
                        {
                            id: "data2",
                            type: "imageButton",

                        },
                        {
                            id: "data3",
                            type: "imageButton",

                        }

                    ];

                    toolbar.data.parse(data);
                    dhxWindow.attach(toolbar);
                    dhxWindow.show();

                    setTimeout(function () {
                        dhxWindow.hide();
                    }, 4000);


                });

What am i doing wrong? Thanks


Solution

  • var myTimeout;
    grid.events.on("CellClick", function (row, column, e) {
                        if(myTimeout) clearTimeout(myTimeout); // cancel timeout if present
                        var data = [
                            {
                                id: "data1",
                                type: "imageButton",
    
    
                            },
                            {
                                id: "data2",
                                type: "imageButton",
    
                            },
                            {
                                id: "data3",
                                type: "imageButton",
    
                            }
    
                        ];
    
                        toolbar.data.parse(data);
                        dhxWindow.attach(toolbar);
                        dhxWindow.show();
    
    
    
    
    
                        myTimeout =  setTimeout(function () {
                            dhxWindow.hide();
                        }, 4000); // Reinstantiate timeout
    
    
    
                    });