Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent Javascript from being executed twice

I have a script that I am developing that creates a sliding button type effect. Five div's are situated next to eachother each with a link. When one of those DIVS are clicked on the associated content is expanded and the rest of the Div's are closed.

The problem is, if a user clicks the Div twice while it loads or clicks another Div in rapid succession, cracks start to show.

I am wondering if it would be possible to only allow the query to be executed once and wait until completion rather than queuing it.

Here is my current code, if it is crap feel free to comment on how I could better it... I am not the best at Javascript/jQuery :P

    function mnuClick(x){
    //Reset all elements
    if($('#'+x).width()!=369){
        $('.menu .menu_Graphic').fadeOut(300);
        $('.menu_left .menu_Graphic').fadeOut(300);
        $('.menu_right .menu_Graphic').fadeOut(300);
        $('.menu').animate({width: "76px"},500);
        $('.menu_left').animate({width: "76px"},500);
        $('.menu_right').animate({width: "76px"},500);
    }
        var ElementId = '#' + x;

        $(ElementId).animate({
            width: 369 + "px"
        },500, function(){ 
            $(ElementId + ' .menu_Graphic').fadeIn(300);
        });
}

Thanks in advance, Chris.

like image 969
Chris Avatar asked Nov 15 '10 15:11

Chris


People also ask

Why is JavaScript running twice?

It's because a <label> with a for attribute raises the click event of <input type="checkbox"> element that is associated for when clicked. You should bind click event handler to input , not to label . Show activity on this post. When you click your label, may it be there is event click runs also on checkbox?

How do you stop a run in JavaScript?

Currently there is no standard way to completely terminate JavaScript. If you need to stop the whole JS process for debugging purposes, use the Developer Tools in Webkit or Firebug on Firefox to set breakpoints by doing debugger; . This will halt absolutely everything from executing.

Can you define a function twice in JavaScript?

functions are data in memory stack, so when you define another function with the same name, it overrides the previous one. Show activity on this post. Well obviously you're not meant to define the same function twice. However, when you do, the latter definition is the only 1 that applies.


1 Answers

You need a "isRunning" flag. Check for it before you start. Set it when you start the sequence, clear it when it ends.

like image 153
Diodeus - James MacFarlane Avatar answered Oct 03 '22 15:10

Diodeus - James MacFarlane