0

JavaScriptには数百のカウントダウンタイマースクリプトがあることは知っていますが、必要なことを実行するスクリプトはまだ見つかっていないので、ここの専門家が助けてくれることを願っています。

基本的に私が探しているのは、この例のように、ある休日から次の休日までカウントダウンするスクリプトです。


Thanksgiving is in: 12 Days 11 hours 25 minutes and 9 seconds
Thanksgiving is in: 12 Days 11 hours 25 minutes and 8 seconds
Thanksgiving is in: 12 Days 11 hours 25 minutes and 7 seconds
Thanksgiving is in: 12 Days 11 hours 25 minutes and 6 seconds
Thanksgiving is in: 12 Days 11 hours 25 minutes and 5 seconds
...
...
...

タイマーが0に達するまで、同じタイマーでこれを表示したいと思います。


Christmas is in: 29 Days 23 hours 59 minutes and 59 seconds
Christmas is in: 29 Days 23 hours 59 minutes and 58 seconds
Christmas is in: 29 Days 23 hours 59 minutes and 57 seconds
Christmas is in: 29 Days 23 hours 59 minutes and 56 seconds
Christmas is in: 29 Days 23 hours 59 minutes and 55 seconds
...
...
...

そして、0に達すると、NewYearsまたはスクリプトで設定された次の日付にカウントダウンを開始し、永久にループします。これを実行できるスクリプトを知っている人はいますか?

ありがとう、アダム

4

4 に答える 4

2
var callbacks = [
    {
        interval: 1000,
        callback: function() {
            // do Timer1 stuff
        }
    },
    {
        interval: 2000,
        callback: function() {
            // do Timer2 stuff
        }
    },
    {
        interval: 3000,
        callback: function() {
            // do Timer3 stuff
        }
    }
];

function startTimer () {
    var callback = callbacks[0];
    window.setTimeout(onTimerComplete, callback.interval);
}

function onTimerComplete () {
    var callback = callbacks.shift();
    callbacks.push(callback); // the first shall be the last
    callback.callback(); // call the callback function
    startTimer(); // set the timer for the first callback
}

startTimer();
于 2010-11-13T22:23:29.957 に答える
2

私は既存の多くのカウントダウン スクリプトの 1 つを変更する方法を提案するつもりでしたが、それらのほぼすべてが現在の JavaScript コーディング標準によってひどく書かれていました (たとえば、setTimeout の引数として文字列を使用するなど)。

だから私は時間をかけて自分で書いてみました試してみてください。クレジットを表示する限り、誰でも自由に使用または変更できます。カウントダウン テキストを挿入<p id="countdown"></p>したい場所に挿入し、次の JavaScript コードを追加して、必要に応じて日付のリストを変更します (例では 5 つを使用しています)。

/*
Date Countdown Widget for JavaScript
Copyright (c) 2010 idealmachine.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/


function startCountdown(dates, elem, format) {
    var now = new Date(), index = 0, targetDate;

    // Returns the next date a specific month/day combination occurs.
    function nextDateOccurs(arr) {
        var monthNotYet = now.getMonth() < arr[0] - 1,
            dayNotYet = now.getMonth() == arr[0] - 1 && now.getDate() < arr[1];

        if(monthNotYet || dayNotYet) {
            // Date will pass within this calendar year
            return new Date(now.getFullYear(), arr[0] - 1, arr[1]);
        } else {
            // Date has already passed within this calendar year
            return new Date(now.getFullYear() + 1, arr[0] - 1, arr[1]);
        }
    }

    // Returns the numeric argument followed by the singular
    // or plural name of the item as is correct (and then
    // a space character).
    function formatQuantity(num, singular, plural) {
        return num + " " + (num == 1 ? singular : plural) + " ";
    }

    // Pick the target date that is closest.
    for(var j = 0; j < dates.length; ++j) {
        if(nextDateOccurs(dates[j]) < nextDateOccurs(dates[index])) {
            index = j;
        }
    }

    // Make a Date object for the target date.
    targetDate = nextDateOccurs(dates[index]);


    // Update the countdown every second.
    function updateCountdown() {
        var months = 0, millis, advNow, advNow1, words = "";

        // Update now with the current date and time.
        advNow1 = now = new Date();

        // Has the target date already passed?
        if(now >= targetDate) {
            millis = 0;
        } else {
            // Find the last time that is a whole number of months past now
            // but less than one month before the target date.
            while(advNow1 < targetDate) {
                ++months;
                advNow = advNow1;
                advNow1 = new Date(now);
                advNow1.setMonth(now.getMonth() + months);
            }
            --months;

            // Find the time difference in milliseconds within the month.
            millis = targetDate - advNow;
        }

        // Turn that into months, days, hours, minutes, and seconds.
        words += formatQuantity(months, "month", "months");
        words += formatQuantity(Math.floor(millis / 864e5), "day", "days");
        words += formatQuantity(Math.floor(millis % 864e5 / 36e5), "hour", "hours");
        words += formatQuantity(Math.floor(millis % 36e5 / 6e4), "minute", "minutes");
        words += formatQuantity(Math.floor(millis % 6e4 / 1e3), "second", "seconds");

        // Update the element.
        elem.innerHTML = format
            .replace(/%NAME%/g, dates[index][2])
            .replace(/%WORDS%/g, words);

    }

    updateCountdown();
    setInterval(updateCountdown, 1000);
}

function countdownSettings() {
    startCountdown([
            // Change the dates here to customize the script.
            [1, 1, "New Year's Day"],
            [2, 14, "Valentine's Day"],
            [7, 4, "Fourth of July"],
            [10, 31, "Halloween"],
            [12, 25, "Christmas"]

        ],
        /* Element to update */ document.getElementById("countdown"),
        /* Format of HTML inserted */ "%NAME% is in: %WORDS%"
    );
}

// Run the script only after the page has fully loaded
// to ensure that elements are accessible from the DOM.
if(window.addEventListener) {
    window.addEventListener("load", countdownSettings, false);
} else {
    window.attachEvent("onload", countdownSettings);
}

改善のための提案を歓迎します。

編集:スクリプトを改善して、その設定をほとんどのコードからより適切に分離し、ページが読み込まれるとすぐにカウントダウンを更新しました。また、目標日はページの読み込み時にのみ選択されるようになりました。つまり、カウントダウンはゼロで停止します (ただし、ページがリロードされると、次の目標日に切り替わります)。

于 2010-11-14T06:06:48.963 に答える
1

私は元の投稿者であり、idealmachine が作成したコードを試してみましたが、これを実際に実行可能なソリューションにする提案が 1 つだけあります。カウントダウン時間に時間と分のサポートを追加できれば、私のニーズにぴったりです. おそらく配列内のこのようなもの

[Month, Day, Hour, Minute, "Tuesdays Meeting"]

時間には 24 時間形式を使用できるため、17 は午後 5 時、5 はもちろん午前 5 時を意味します。これにより、スクリプトははるかに多くの人に開かれ、私のニーズに最適になります.

ありがとう、アダム

于 2010-11-14T12:33:47.457 に答える
0

これは出発点です。必要な詳細についてはわかりませんが、これはタイマーを開始し、完了すると(5秒後)2番目のタイマー(4秒続く)を開始します。

<div id="countDiv"></div>

<script>
function countDown1 (count) {
  if (count > 0) {
   var d = document.getElementById("countDiv");
   d.innerHTML = "counter 1: " + count;
   setTimeout ("countDown1(" + (count-1) + ")", 1000);
   }
  else
   countDown2(4);
}
function countDown2 (count) {
  if (count > 0) {
   var d = document.getElementById("countDiv");
   d.innerHTML = "counter 2: " + count;
   setTimeout ("countDown2(" + (count-1) + ")", 1000);
   }

}
countDown1(5);
</script>
于 2010-11-13T22:13:32.070 に答える