1

オーディオは、私のホームページの背景に組み込まれた目覚まし時計のように、特定の時間に再生されるように設定されています。正しい時間に再生されます。ただし、何らかの理由で Web ページの読み込みでも再生されます。私は無知なので、誰かがそれを理解できるなら、それは非常にありがたいです。

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);
4

1 に答える 1

1

正午を過ぎているため、timeout1 は負の値です。少なくとも私のタイムゾーン EST では。したがって、おそらく正の時間の条件を追加する必要があります。

次のようなif句でタイムアウトをラップするだけです。

if(timout1 > 0){
setTimeout(function(){
    if (weekday > 0 && weekday < 6) {
        audio.play();
    }
}, timeout1);
}

また、タイムアウトごとにすべてを書き換えないように、これを再構築します。

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]);
    }
}

編集:タイプミスによるエラーを修正しました。

于 2013-05-09T17:29:04.420 に答える