javascript - Changing the background <body> background color switching css ids using recursive function -
i'm trying change body background color flashes id change using recursive function, functions even/odd condition check , continues incrementing supplied parameter after each excution. i'm executing function using dom level 0 event handler on-click. i'm seeing weird results.
here html/css javascript code. see comments put in code, explains other weird problems.
<head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>untitled document</title> <style> #style1 { background:red; } #style2 { background:black; } </style> </head> <body> <input name="" type="button" value="style changer" id="button1" /> <script> var button = document.getelementbyid("button1"); var background = function (y) { alert(y); // results of background change or rest of code works if alert there don't understand if(y % 2 === 0) { alert(y); // weird result: shows 2 no reason. document.body.id = "style1"; // value supplied parameter y 1 taking css property suppose take when y number. var y = y + 1; background(y); } // end if else { document.body.id = "style2"; var y = y + 1; background(y); } //end else } // end of function button.onclick = function () { var x = 1; background(x); } // big problem: last not least remove alert function , not work worked when there alerts in code. </script> </body>
i not quite sure actual problem want solve.
but code results in infinite loop in return results in exception (check console output):
maximum call stack size exceeded
this is, because recursive calls happen fast. when use alert, code execution paused long alert box shown.
you can counteract code 'running fast' adding small time delay:
var delay = 300; // 300ms delay var background = function(y){ if( y%2 === 0){ document.body.id = 'style1'; settimeout(function(){ background(y+1) }, delay); } else { document.body.id = 'style2'; settimeout(function(){ background(y+1) }, delay); } }
working example: http://jsfiddle.net/d7pbx/
update 1: fast flashing
also note, can change delay 0
result in fast flickering of background, might intended.
update 2: stacking timeouts
as pointed out @rdp repeated clicking of button result in stacking of timeout calls. if want prevent happening, clear previous timeout before creating new one:
cleartimeout(t); t = settimeout(function(){ backgound(y+1) }, delay);
working example: http://jsfiddle.net/rutxu/2/
or allow 1 settimeout call @ time setting boolean:
if(busy) return; busy = true; settimeout(function(){ busy = false; backgound(y+1) }, delay);
working example: http://jsfiddle.net/rutxu/3/
but of course, of depends on specific use case
Comments
Post a Comment