javascript - How to stop setInterval loop -
i've setup setinterval alter colour of div using different css classes. start changing colours pressing button, want stop changing colours using same button. can't work. here js:
var bsstyles = ["alert alert-success","alert alert-info","alert alert-warning","alert alert-danger"]; var = 0; var buttonstate = false; var runner; var mainfun = function () { if (buttonstate == 0) { buttonstate = true; document.getelementbyid("changebutton").classname = "btn btn-primary btn-lg active"; var runner = setinterval(function() { document.getelementbyid("alertw").classname = bsstyles[i]; i++; if (i==bsstyles.length) { i=0; } },1000); } else { clearinterval(runner); document.getelementbyid("changebutton").classname = "btn btn-primary btn-lg"; buttonstate = false; } } var changebutton = document.getelementbyid("changebutton"); changebutton.addeventlistener('click',mainfun,false);
here jsfiddle
when define mainfun
need remove var keyword before 'runner'
by using var keyword there defining new local variable no longer references global variable runner
so code should like
var bsstyles = ["alert alert-success","alert alert-info","alert alert-warning","alert alert-danger"]; var = 0; var buttonstate = false; var runner; var mainfun = function () { if (buttonstate == 0) { buttonstate = true; document.getelementbyid("changebutton").classname = "btn btn-primary btn-lg active"; runner = setinterval(function() { document.getelementbyid("alertw").classname = bsstyles[i]; i++; if (i==bsstyles.length) { i=0; } },1000); } else { clearinterval(runner); document.getelementbyid("changebutton").classname = "btn btn-primary btn-lg"; buttonstate = false; } } var changebutton = document.getelementbyid("changebutton"); changebutton.addeventlistener('click',mainfun,false);
javascript setinterval
No comments:
Post a Comment