Reputation: 2577
So this is what my Javascript looks like:
function open_box(message){
var box_content = '<div id="overlay"><div id="box_frame"><div id="box">'+message+'<a href="javascript:reset_frame()"><div id="xbutton"><img src="elements/xbutton.png"></div></a></div></div></div>';
document.getElementById('functioner').innerHTML = box_content;
open_box('Why hello there');
}
When I fill in the 'Why hello there' parameter in my JS file, it prints just like it should in HTML. For all intents and purposes, the function works. The only problem is that it takes quite a while to load. To the point where sometimes my browser asks to stop the operation. Can anyone explain to me why this is? Any potential avenues for optimization?
EDIT: I see your guys' point about recursion. Looking back at it, it makes sense. This leads me to another problem.
When moved directly outside the function, my HTML doesn't acknowledge my 'why hello there' parameter. The code that is meant to call it is just a simple <a href="javascript:open_box()">
.
I'm still trying to get into the hang of calling JS code, so excuses for the newbie mistake.
Upvotes: 1
Views: 143
Reputation: 239503
You are falling into infinite recursion. when open_box
is called the first time, the last statement in it is to call open_box
itself and this happens infinitely. So, to fix it change
function open_box(message){
var box_content = '<div id="overlay"><div id="box_frame"><div id="box">'+message+'<a href="javascript:reset_frame()"><div id="xbutton"><img src="elements/xbutton.png"></div></a></div></div></div>';
document.getElementById('functioner').innerHTML = box_content;
open_box('Why hello there');
}
to
function open_box(message){
var box_content = '<div id="overlay"><div id="box_frame"><div id="box">'+message+'<a href="javascript:reset_frame()"><div id="xbutton"><img src="elements/xbutton.png"></div></a></div></div></div>';
document.getElementById('functioner').innerHTML = box_content;
}
open_box('Why hello there');
Upvotes: 3
Reputation: 20567
This is because of recursion, the function is calling itself over and over again
Each time the function calls its self it is changing the DOM and then calling its self again, eventually causing a stack overflow error.
Move open_box('Why hello there');
to out side the function, like so:
function open_box(message){
var box_content = '<div id="overlay"><div id="box_frame"><div id="box">'+message+'<a href="javascript:reset_frame()"><div id="xbutton"><img src="elements/xbutton.png"></div></a></div></div></div>';
document.getElementById('functioner').innerHTML = box_content;
}
//Moved to outside the function
open_box('Why hello there');
More info on recursion: http://en.wikipedia.org/wiki/Recursion
Also if you look in your console (F12, then console in chrome) you should see this: Maximum call stack size exceeded error
Upvotes: 2