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

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -