开发者

Prevent Javascript from being executed twice

开发者 https://www.devze.com 2023-01-24 23:23 出处:网络
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 conten

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 a开发者_如何学Gollow 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.


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


(function() {
var mutex = false;

    function mnuClick(x){
        if (!mutex) {
           mutex = !mutex;

           /* all code here ...   */

           mutex = !mutex; /* this statement should go into animation callback */
        }

    }

})();

mantain a state through a variable so you cannot click more than once until code has fully executed


you can unplug the onClick event handler (mnuClick) when the event starts, to effectively disable invoking the mnuClick twice, but be sure to restore it when the event ends.


Quick answer: use .addClass and .removeClass and test for the existence of the class at execution time. Test if it's set and return, or add it, execute the code, then remove it.


you can create an invisible maskin and maskout ( like the background in lightbox etc ) or disable clicks until the animation finishes.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号