Your code has a few problems.(您的代码有一些问题。)
First, in your definition:(首先,在你的定义中:)
var shrink = function(p) {
for (var i = 0; i < 100; i++) {
p.radius -= 1;
}
function asplode(p) {
setInterval(shrink(p),100);
balls.splice(p, 1);
}
}
asplode
is local to the scope inside shrink
and therefore not accessible to the code in update
where you are attempting to call it.(asplode
是shrink
范围内的本地,因此在您尝试调用它时update
中的代码无法访问。) JavaScript scope is function-based, so update
cannot see asplode
because it is not inside shrink
.(JavaScript范围是基于函数的,因此update
无法看到asplode
因为它不在内部shrink
。) ( In your console , you'll see an error like: Uncaught ReferenceError: asplode is not defined
.)(( 在您的控制台中 ,您将看到如下错误: Uncaught ReferenceError: asplode is not defined
。))
You might first try instead moving asplode
outside of shrink
:(您可能首先尝试在非shrink
之外移动asplode
:)
var shrink = function(p) {
for (var i = 0; i < 100; i++) {
p.radius -= 1;
}
}
function asplode(p) {
setInterval(shrink(p),100);
balls.splice(p, 1);
}
However, your code has several more problems that are outside the scope of this question:(但是,您的代码还有几个问题超出了本问题的范围:)
setInterval
expects a function.(setInterval
需要一个函数。) setInterval(shrink(p), 100)
causes setInterval
to get the return value of immediate-invoked shrink(p)
.(setInterval(shrink(p), 100)
使setInterval
获取立即调用的 shrink(p)
的返回值 。) You probably want(你可能想要) setInterval(function() { shrink(p) }, 100)
Your code for (var i = 0; i < 100; i++) { p.radius -= 1; }
(你的代码for (var i = 0; i < 100; i++) { p.radius -= 1; }
) for (var i = 0; i < 100; i++) { p.radius -= 1; }
probably does not do what you think it does.(for (var i = 0; i < 100; i++) { p.radius -= 1; }
可能不会做你认为它。) This will immediately run the decrement operation 100 times, and then visually show the result.(这将立即运行减量操作100次, 然后直观地显示结果。) If you want to re-render the ball at each new size, you will need to perform each individual decrement inside a separate timing callback (like a setInterval
operation).(如果要以每个新大小重新渲染球,则需要在单独的定时回调中执行每个单独的减量(如setInterval
操作)。)
.splice
expects a numeric index, not an object.(.splice
需要一个数字索引,而不是一个对象。) You can get the numeric index of an object with indexOf
:(您可以使用indexOf
获取对象的数字索引:) balls.splice(balls.indexOf(p), 1);
By the time your interval runs for the first time, the balls.splice
statement has already happened (it happened about 100ms ago, to be exact).(当你的间隔第一次运行时, balls.splice
语句已经发生了( balls.splice
它发生在大约100ms前)。) I assume that's not what you want.(我认为这不是你想要的。) Instead, you should have a decrementing function that gets repeatedly called by setInterval
and finally performs balls.splice(p,1)
after p.radius == 0
.(相反,你应该有一个由setInterval
重复调用的递减函数,最后在p.radius == 0
之后执行balls.splice(p,1)
。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…