Problem
http://jsfiddle.net/goldrunt/jGL84/42/ This is from the JS fiddle’s line 84. By uncommenting lines 141-146, you may apply three distinct effects to the balls. The ‘bounce’ effect is effective, but the ‘asplode’ effect has no effect. Should I include the ‘shrink’ function inside the asplode function?
// balls shrink and disappear if they touch
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);
}
}
Asked by MattO
Solution #1
There are a few issues with your code.
To begin with, 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 only visible to the scope inside shrink, not to the code in update where you’re trying to call it. Because the JavaScript scope is function-based, update will not be able to view asplode because it is not contained within shrink. (You’ll get an error like Uncaught ReferenceError: asplode is not defined in your console.)
Instead, you may try moving asplode outside of shrink:
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, there are several more issues with your code that are beyond the scope of this question:
Answered by apsillers
Solution #2
setInterval(shrink(p),100);
This isn’t going to do what you think it’s going to do. This calls shrink, sends it p, and then calls setInterval with the result. This line doesn’t actually put anything on an interval because shrink(p) returns undefined.
You probably want:
setInterval(function(){
shrink(p)
}, 100);
Answered by Rocket Hazmat
Post is based on https://stackoverflow.com/questions/20550930/why-arent-my-ball-objects-shrinking-disappearing