javascript - I have issue with setTimeout/clearTimeout -
i have following js
document.addeventlistener("domcontentloaded", function() { document.queryselector("#pageredirect").addeventlistener("change", changehandler); }); function changehandler() { var timer; if (pageredirect.checked) { timer = settimeout(function() { window.location.href = 'http://www.google.com'; }, 3000); console.log(pageredirect.checked); } else { //dont redirect cleartimeout(timer); console.log(pageredirect.checked); } }
<input type="checkbox" id="pageredirect" name="pageredirect" />
i dont redirect when checkbox uncheck is. where's fault ?
thanks.
the issue location of variable declaration timer id. it's inside function, when attempt clear it, it's not got id assigned in settimeout
. need move declaration outside of function can keep handle of timer between invocations:
var timer; function changehandler(){ // etc
this compounded the spec cleartimeout
says:
if handle not identify entry in list of active timeouts of windowtimers object on method invoked, method nothing.
i.e. silently ignore invalid timer handles, in case undefined
.
Comments
Post a Comment