Apply DRY principle with JavaScript -
i stuck trying apply dry principle in scenario. here code. can see, trying run scripts containing different variables on different days. mean, shoot out bunch of else if statements until friday, not seem right way things. pointers?
thanks
<script> function timer(){ window.alert("the timer start in 1 minute. ready!"); var dayvar = new date().getday(); if(dayvar == 1){ var monphp = "<?php echo $homemon2 ?>"; var min = 60 * monphp; setinterval(function(){ var = new date(); document.getelementbyid("result").innerhtml = "minutes : " + min ; min--; if(min == -1){ window.alert("times up!"); min = 60 * monphp; } },60000); } else if (dayvar == 2){ var tuephp = "<?php echo $hometue2 ?>"; var min = 60 * tuephp; setinterval(function(){ var = new date(); document.getelementbyid("result").innerhtml = "minutes : " + min ; min--; if(min == -1){ window.alert("times up!"); min = 60 * tuephp; } },60000); } } </script>
in php, create array
<?php $arr = array($homesun2, $homemon2, $hometue2, $homewed2 ... etc); ?> then use it
function timer(){ var days = <?php echo json_encode($arr); ?>; var dayvar = new date().getday(); window.alert("the timer start in 1 minute. ready!"); var min = 60 * days[dayvar]; var temp = min; setinterval(function(){ var = new date(); document.getelementbyid("result").innerhtml = "minutes : " + (temp--) ; if(temp == -1){ window.alert("times up!"); temp = min; } },60000); }
Comments
Post a Comment