Countdown Timer is not showing in javascript -
i new in javascript, want create countdown timer localstorage starts given time , end 00:00:00, it's not working, when running code showing value "1506".
here code
<script type="text/javascript"> if (localstorage.getitem("counter")) { var currenttime = localstorage.getitem("counter"); } else { var hour = 3; var minute = 25; var second = 60; var currenttime = hour.tostring() + ":" + minute.tostring() + ":" + second.tostring(); } function countdown() { document.getelementbyid('lblduration').innerhtml = currenttime; second--; if (second == -1) { second = 59; minute--; } if (minute == -1) { minute = 59; hour--; } localstorage.setitem("counter", currenttime); } var interval = setinterval(function () { countdown(); }, 1000); </script>
when localstorage available don set values hour, minute , second. when countdown function executed finds second undefined , statement second-- converts second nan. fix initialize hour, minute , second variable. 've refactored code little bit hope helps:
function countdown() { var currenttime = getcurrenttime(); printcurrenttime(currenttime) currenttime.second--; if (currenttime.second == -1) { currenttime.second = 59; currenttime.minute--; } if (currenttime.minute == -1) { currenttime.minute = 59; currenttime.hour--; } setcurrenttime(currenttime); } function setcurrenttime(newcurrenttime){ if(localstorage) localstorage.setitem("counter", json.stringify(newcurrenttime)); else setcurrenttime.storage = newcurrenttime; } function getcurrenttime(){ var result = localstorage ? localstorage.getitem("counter") : setcurrenttime.storage; result = result || {hour:3, minute:25, second:60}; if (typeof(result) === "string")result = json.parse(result); result.tostring = function(){ return result.hour + ":" + result.minute + ":" + result.second; } return result; } function printcurrenttime(currentime){ var domtag = document.getelementbyid('lblduration'); if(domtag) domtag.innerhtml = currentime.tostring(); else console.log(currentime); } setinterval(function () { countdown(); }, 1000);
Comments
Post a Comment