javascript - Audio Sound Playing onload when its supposed to be a timed event -
the audio set play @ times, alarm clock built background of home page. it's playing @ correct times. however, it's playing on loading of web page reason. if can figure out that'd appreciated clueless.
var date = new date(), year = date.getfullyear(), month = date.getmonth(), weekday = date.getday(), day = date.getdate(), time = date.gettime(), timeout1 = new date(year, month, day, 12, 15, 0, 0).gettime() - time, timeout2 = new date(year, month, day, 14, 30, 0, 0).gettime() - time, timeout3 = new date(year, month, day, 17, 0, 0, 0).gettime() - time, timeout4 = new date(year, month, day, 19, 0, 0, 0).gettime() - time, timeout5 = new date(year, month, day, 23, 45, 0, 0).gettime() - time, mp3 = new audio("audio/alarm.mp3"), ogg = new audio("audio/alarm.ogg"), audio; if (typeof mp3.canplaytype === "function" && mp3.canplaytype("audio/mpeg") !== "") audio = mp3; else if (typeof ogg.canplaytype === "function" && ogg.canplaytype("audio/ogg") !== "") audio = ogg; settimeout(function(){ if (weekday > 0 && weekday < 6) { audio.play(); } }, timeout1); settimeout(function(){ if (weekday > 0 && weekday < 6) { audio.play(); } }, timeout2); settimeout(function(){ if (weekday > 0 && weekday < 6) { audio.play(); } }, timeout3); settimeout(function(){ if (weekday > 0 && weekday < 6) { audio.play(); } }, timeout4); settimeout(function(){ if (weekday > 0 && weekday < 6) { audio.play(); } }, timeout5);
timeout1 negative value because after 12 noon. @ least in timezone est. should add condition positive times.
you can wrap timeouts in if clause like:
if(timout1 > 0){ settimeout(function(){ if (weekday > 0 && weekday < 6) { audio.play(); } }, timeout1); }
also, restructure limit rewriting each timeout.
var date = new date(), year = date.getfullyear(), month = date.getmonth(), weekday = date.getday(), day = date.getdate(), time = date.gettime(), timeouts = [], timeouts.push(new date(year, month, day, 12, 15, 0, 0).gettime() - time), timeouts.push(new date(year, month, day, 14, 30, 0, 0).gettime() - time), timeouts.push(new date(year, month, day, 17, 0, 0, 0).gettime() - time), timeouts.push(new date(year, month, day, 19, 0, 0, 0).gettime() - time), timeouts.push(new date(year, month, day, 23, 45, 0, 0).gettime() - time), mp3 = new audio("audio/alarm.mp3"), ogg = new audio("audio/alarm.ogg"), audio; if (typeof mp3.canplaytype === "function" && mp3.canplaytype("audio/mpeg") !== "") audio = mp3; else if (typeof ogg.canplaytype === "function" && ogg.canplaytype("audio/ogg") !== "") audio = ogg; for(var i=0;i<timeouts.length;i++){ if(timeouts[i] > 0){ settimeout(function(){ audio.play(); }, timeouts[i]); } }
edit: corrected error due typos.
Comments
Post a Comment