Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/375.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么赢了';这两个看似相同的实现是否都会导致溢出?_Javascript_Jquery - Fatal编程技术网

Javascript 为什么赢了';这两个看似相同的实现是否都会导致溢出?

Javascript 为什么赢了';这两个看似相同的实现是否都会导致溢出?,javascript,jquery,Javascript,Jquery,正如预期的那样,下面的jquery函数 $(document).ready(function animate1(){ var div = $("#circle"); var xcor,ycor; xcor = Math.random()*100; ycor=Math.random()*100; div.animate({left: xcor, top:ycor}, "slow", animate1()); }); 将导致堆栈溢出 但是为什么呢 下面的函数不

正如预期的那样,下面的jquery函数

$(document).ready(function animate1(){

    var div = $("#circle"); 
    var xcor,ycor;
    xcor = Math.random()*100; ycor=Math.random()*100;

    div.animate({left: xcor, top:ycor}, "slow", animate1());
});
将导致堆栈溢出 但是为什么呢 下面的函数不支持吗

$(document).ready(function animate1(){

    var div = $("#circle"); 
    var xcor,ycor;
    xcor = Math.random()*100; ycor=Math.random()*100;

    div.animate({left: xcor, top:ycor}, "slow", function () {animate1();});
});

在第一种情况下,您正在调用
div.animate
的过程中执行
animate1()
。这就是导致溢出的原因。在第二种情况下,你不是;完成函数仅在动画完成后调用
animate1()
。在第一种情况下,可以尝试使用
animate1
而不是
animate1()
作为完成参数

div.animate({left: xcor, top:ycor}, "slow", animate1);
您将立即在此处调用animate1,而不是为animate提供函数引用。这意味着逻辑将启动一个非常快速的无止境递归循环,而不释放以前获得的资源

div.animate({left: xcor, top:ycor}, "slow", function () {animate1();});
这个函数提供了一个正确的回调,它不会导致立即调用,并允许释放资源

div.animate({left: xcor, top:ycor}, "slow", function () {animate1();});