代码之家  ›  专栏  ›  技术社区  ›  helloandre

再次调用setTimeout将停止第一个实例

  •  0
  • helloandre  · 技术社区  · 15 年前

    我有一个用javascript编写的小游戏,可以在你点击的地方创建一个波浪。我想出了两种让“波浪”在屏幕上移动的方法:

    1. 调用jQuery.animate()的时间越来越长。 demo
    2. 通过递归调用setTimeout。 demo

    现在在第二个演示中,如果在“wave”结束之前再次单击,它会立即清除设置超时并重新启动。我希望能够像第一个示例中那样堆叠它们。

    您可以查看其中任何一个页面的源代码以查看代码(方法是getMouseXYUp和getMouseXYDown)。

    我在第二个演示中所做工作的基本要点可以在以下两个函数中找到:

    function getMouseXYUp(e) {
                $("body").die('mousemove');
    
                h = (document.height - e.pageY + 17);
                    left = id-1;
                    right = id+1;
                setTimeout("moveleft()", 100);
                setTimeout("moveright()", 100);
    
                return true
            }
    
    function moveleft(){
            if (left >= 0){
                $("#div"+left).animate({'height': h}, 400);
                left--;
                setTimeout("moveleft()", 50);
            }
        }
    
    2 回复  |  直到 15 年前
        1
  •  2
  •   edsoverflow    15 年前

    问题是,当第二次鼠标单击时,您正在重置变量“left”和“right”。这和你要找的更接近吗?

        function getMouseXYUp(e) {
            $("body").die('mousemove');
    
            var h = (document.height - e.pageY + 17);
            var left = id-1;
            var right = id+1;
            setTimeout(function() { moveleft(left, h); }, 100);
            setTimeout(function() { moveright(right, h); }, 100);
    
            return true;
        }
    
        ...
    
        function moveleft(left, h) {
            if (left >= 0){
                $("#div"+left).animate({'height': h}, 400);
                left--;
                setTimeout(function() { moveleft(left, h); }, 50);
            }
        }
    
        function moveright(right, h) {
            if (right < divs){
                $("#div"+right).animate({'height': h}, 400);
                right++;
                setTimeout(function () { moveright(right, h); }, 50);
            }
        }
    
        2
  •  0
  •   epascarello    15 年前

    查看代码,似乎您在全局变量方面存在问题。您需要在函数调用中左右传递,而不是在全局范围中传递。