防止在当前函数执行完成之前执行jQuery函数

3

我在jQuery中有一个函数,每当我按下任何箭头键时就会触发它。以下是“向上”箭头情况的代码,其他三种情况看起来非常相似,都包含在checkKey函数中。

document.onkeydown = checkKey;

    function checkKey(e) {
        var divs = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen"];
        e = e || window.event;

        if (e.keyCode == '38') {
            for (i = 0; i < divs.length; i++){
                var tmp = document.getElementById(divs[i]);
                var coord = $(tmp).position();
                if ((Math.abs(embargo_top - coord.top) < 115) && (Math.abs(embargo_left - coord.left) < 15)){
                    if(embargo_top < coord.top){
                        embargo_top = coord.top;
                        embargo_left = coord.left;
                        $(tmp).animate({
                            'top': (parseInt($(tmp).css('top'), 10) - 100) + "px"
                        }, 500);
                        break;
                    }
                }
            }
            checkIfWinner();
        }

我该如何处理这些事件,以便如果我连续按下一堆箭头键,每个函数的执行仅在前一个函数调用完全完成后才发生?


https://dev59.com/VGs05IYBdhLWcg3wPPWB - Khanh TO
2个回答

1
有很多方法可以做到这一点。一种方法是将它们添加到队列中,该队列一次只能执行一项任务。在每个函数中,完成后出队,以便下一个函数可以运行。您可以使用jQuery的queue函数:http://api.jquery.com/jquery.queue/

0

看起来你正在为多个对象添加动画,而且你想在所有动画停止之前避免任何按键输入。尝试进行以下更改(由箭头==>突出显示):

document.onkeydown = checkKey;

==> var animationStillGoing = 0;

    function checkKey(e) {
        var divs = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen"];
        e = e || window.event;

==>         if (animationStillGoing>0) {return}

        if (e.keyCode == '38') {
            for (i = 0; i < divs.length; i++){
                var tmp = document.getElementById(divs[i]);
                var coord = $(tmp).position();
                if ((Math.abs(embargo_top - coord.top) < 115) && (Math.abs(embargo_left - coord.left) < 15)){
                    if(embargo_top < coord.top){
                        embargo_top = coord.top;
                        embargo_left = coord.left;

                        animationStillGoing++;

                        $(tmp).animate({
                            'top': (parseInt($(tmp).css('top'), 10) - 100) + "px"
==>                           }, 500,function(){animationStillGoing--;});
                        break;
                    }
                }
            }
            checkIfWinner();
        }

这些更改的作用是让全局变量跟踪正在进行的动画。该值从0开始,keyCheck函数将返回此值是否> 0。
在动画开始之前,animationStillGoing将增加,并在动画结束时减少。因此,如果仍有三个动画正在进行,则此参数将为3,如果新动画开始,则它将变为4,并且只有当所有动画都完成时才会返回值0。一旦达到0,keyCheck将继续工作。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接