jQuery timer/countdown using server time

2019-09-09 12:35发布

问题:

I'm trying to have a countdown for every 10 minutes (according to the server time, not client). Every 10 minutes (eg. 10am, 10:10am, 10:20:am [on the tens]) it needs to refresh the page and start over.

I've found timeout functions but none that use the server time and that I can have reset on the tens.

Has anyone done anything like this before?

Thanks

回答1:

You can render the start of the timer form server side and then use it to control the timer logic on the server side.

E.g.

var timerStart = new Date("dateString");//Render this from server side

And then use timerStart variable in countdown logic.

Some examples to create a new Date in JavaScript.

new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)


回答2:

Im not all that familiar with C#, so pardon the PHP example, but the concept is the same. In your Javascript, create a variable that holds the length of time until the next refresh..

<script>
    var firstRefresh=<?php echo $numberOfMiliSecondsToFirstRefresh; ?>;
</script>

Then you can set your first timer to refresh in that amount of time, and from then on out, you can just refresh every 10 minutes...



回答3:

I ended up using some of the ideas in comments/answers and other posts and came up with this.

It counts down every 10 minutes (again, according to the server) and displays the timer value. When it reaches "0" (-1:59) it will reload the page and start over at 10 minutes.

May not be the cleanest code, but it seems to work pretty well:

<script>
var currentMin = @DateTime.Now.Minute;
var currentSec = @DateTime.Now.Second;
var minutesLeft = 0;
var secondsLeft = 0;

$(document).ready(function() {
    setupTimer();
});

function setupTimer() {
    var baseMins = 0;
    if (currentMin >= 0 && currentMin <= 9)
        baseMins = 10;
    else if (currentMin >= 10 && currentMin <= 19)
        baseMins = 20;
    else if (currentMin >= 20 && currentMin <= 29)
        baseMins = 30;
    else if (currentMin >= 30 && currentMin <= 39)
        baseMins = 40;
    else if (currentMin >= 40 && currentMin <= 49)
        baseMins = 50;
    else if (currentMin >= 50 && currentMin <= 59)
        baseMins = 60;

    minutesLeft = (baseMins - 1) - currentMin;
    secondsLeft = 60 - currentSec;

    setInterval(decreaseTimer, 1000);
}

function decreaseTimer() {
    secondsLeft--;
    if (secondsLeft == -1) {
        minutesLeft--;
        secondsLeft = 59;
    }
    if (minutesLeft == -1 && secondsLeft == 59) {
        location.reload();
    }
    displayTimer();
}

function displayTimer() {
    if (minutesLeft == 0)
        minutesLeft = "0";
    if (secondsLeft < 10)
        secondsLeft = "0" + secondsLeft;
    var timerDisplay = minutesLeft + ":" + secondsLeft;
    $("#timer").text(timerDisplay);
}
</script>


标签: c# jquery timer