javascript - When clicked on a button that handles event more than one time setInterval goes crazy? -
when click in automatic button (auto) more once, handles setinterval method, color divs go crazy fast, reason i'm here know. demo in jsfiddledemo of color divs setinterval method
body:
<div id="placediv1">ok</div> <button id="b1" onclick="forward()">forward</button> <button id="b2" onclick="backward()">backward</button> <button id="b3" onclick="skip2()">skip2</button> <button id="b4" onclick="automatic()">auto</button> <button id="b5" onclick="stop()">stop</button> <script> var myarray = ["black", "yellow", "green", "red", "blue", "blue", "black", "gray"]; var myarray1 = ["yellow", "blue", "green", "red", "green", "blue", "black", "gray"]; var = 0; document.getelementbyid("placediv").style.backgroundcolor = myarray[i]; document.getelementbyid("placediv1").style.backgroundcolor = myarray1[i]; forward = function () { if (i == myarray.length - 1) { = 0; } else { = + 1; } document.getelementbyid("placediv1").style.backgroundcolor = myarray1[i]; document.getelementbyid("placediv").style.backgroundcolor = myarray[i]; }; skip2 = function () { if (i == myarray.length - 4) { += 2; alert("this iterator " + i) } else if (i == 7) { = 0 } else { = + 1; }; document.getelementbyid("placediv1").style.backgroundcolor = myarray1[i]; document.getelementbyid("placediv").style.backgroundcolor = myarray[i]; }; backward = function () { if (i == 0) { = myarray.length - 1; = myarray1.length - 1; } else { = - 1; } document.getelementbyid("placediv1").style.backgroundcolor = myarray1[i]; document.getelementbyid("placediv").style.backgroundcolor = myarray[i]; // } automatic = function () { var m = setinterval(function () { if (i == myarray.length - 1) { = 0; } else { = + 1; } document.getelementbyid("placediv1").style.backgroundcolor = myarray1[i]; document.getelementbyid("placediv").style.backgroundcolor = myarray[i]; }, 100); stop = function () { clearinterval(m) }; }; </script>
css:
#placediv { position: absolute; left: 0px; width: 100px; height: 100px; } #placediv1 { position: absolute; left: 100px; width: 100px; height: 100px; } #b1 { position: absolute; top: 100px; left: 0px } #b2 { position: absolute; top: 100px; left: 80px } #b3 { position: absolute; top: 100px; left: 170px } #b4 { position: absolute; top: 100px; left: 270px } #b5 { position: absolute; top: 100px; left: 320px }
just update script like
var m=null; automatic=function(){ clearinterval(m); m = setinterval(function(){ if(i == myarray.length-1) {i=0;} else {i=i+1;} document.getelementbyid("placediv1").style.backgroundcolor = myarray1[i]; document.getelementbyid("placediv").style.backgroundcolor = myarray[i]; },100); stop=function(){ clearinterval(m); };
check fiddle
you need kill setinterval when call function automatic
, need define var m
outside function
Comments
Post a Comment