I try to make a little game but if I start it it says : Uncaught RangeError: Maximum call stack size exceeded" What's wrong with my code? ;-)
function move(top,left){
y_ball = $('#ball').offset().top - $('#spielfeld').offset().top;
x_ball = $('#ball').offset().left - $('#spielfeld').offset().left;
x_balken = $('#balken').offset().left - $('#spielfeld').offset().left;
ball = document.getElementById('ball');
balken = document.getElementById('balken');
if(y_ball >= 0 && y_ball < 465 && x_ball >= 0 && x_ball <= 500){
ball.style.top = y_ball + top + "px";
ball.style.left = x_ball + left + "px";
setTimeout(move, 20 , top, left);
return false;
}
if(y_ball == 0 || x_ball == 0 || x_ball == 500 || y_ball > 465){
top = - top;
left= - left;
move(top,left);
return false;
}
if(y_ball >= 465){
if(-19 < x_ball - x_balken < 59){
top = - top;
left= - left;
move(top,left);
}
}
}
Suppose x_ball, y_ball, top, and left are all zero. You'll generate an infinite series of recursive calls to "move(0,0)", which will exhaust your stack.
JavaScript is an event driven language. Using setInterval
can work. But there are event driven solutions as well:
Use events from awe. I don't have an experience with awe but maybe there is a load
or ready
event you can listen to.
MutationObservers. This is a native API (supported by all modern browsers). It allows you to listen to changes to the DOM. Look for your node in the change list.
MutationObserver is a good solution if you're targeting modern browsers (>= IE 11).
Here's an example:
var parentDiv = document.createElement('div')
var observer = new MutationObserver(function (event) {
console.log("childList changed");
console.dir(event);
});
observer.observe(parentDiv, {
childList: true
});
parentDiv.appendChild(document.createElement('div'))
Otherwise you can fall back to using setInterval
©2020 All rights reserved.