javascript / jquery time count down

不打扰是莪最后的温柔 提交于 2019-12-05 11:13:07

You could use jQuery Countdown

Take a look at this one: http://keith-wood.name/countdown.html

It can be done in JavaScript without plugins.

You need to get the current date time, down to the denominator that is one smaller than what you are displaying. With your example, this would mean you need to get everything down to milliseconds.

var currentTime = new Date(n.getFullYear(), n.getMonth(), n.getDate(), n.getHours(), n.getMinutes(), n.getSeconds(), n.getMilliseconds());

You then find the difference between now and the desired time. This is given to you in milliseconds.

var diff = endtime - currentTime;

Because this is returned in milliseconds you need to convert them into seconds, minutes, hours, days etc... This means establishing how many milliseconds are in each denominator. Then you are able to use mod and divide to return the number needed for each unit. See below.

var miliseconds = 1;
var seconds = miliseconds * 1000;
var minutes = seconds * 60;
var hours = minutes * 60;
var days = hours * 24;
var years = days * 365;

//Getting the date time in terms of units
//Floored so that they go together (to get just year/days/hours etc.. by themselves you need to use Math.round(diff/desired unit);
var numYears = Math.floor(diff / years);
var numDays = Math.floor((diff % years) / days);
var numHours = Math.floor((diff % days) / hours);
var numMinutes = Math.floor((diff % hours) / minutes);
var numSeconds = Math.round((diff % minutes) / seconds);

Once you have the denominators you want to display you can return this to the html page through different methods. For example:

document.getElementById("tyears").innerHTML = numYears;

That sums up your method. However, to make it run on a set interval (which is why you update the HTML display within the JavaScript function) you need to call the following function, giving your function name and provide your interval in terms of milliseconds.

//Call the count down timer function every second (measured in miliseconds)
setInterval(countDown(endtime), 1000);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!