Javascript отсчет дней от

How to write a countdown timer in JavaScript? [closed]

Want to improve this question? Update the question so it focuses on one problem only by editing this post.

Just wanted to ask how to create the simplest possible countdown timer. There’ll be a sentence on the site saying:

So, what I want to do is to create a simple js countdown timer that goes from «05:00» to «00:00» and then resets to «05:00» once it ends. I was going through some answers before, but they all seem too intense (Date objects, etc.) for what I want to do.

And again, you’re leaving out the relevant HTML, though at least you’ve sort of explained the complexity issue this time. But seriously, you need to look into making a solution yourself, and then come and ask us about problems you’re having.

Code examples with complaints on how they are too complicated? Anyway, I think you could easily setInterval and make it .innerHTML based, instead of date based.

Yes, people should look for making the solution themselves. But with javaScript there are plenty examples of doing common tasks. I know how to do a count down timer, but I prefer if I find one in the web (like a component). So thanks to this question and the extensive answer I found what I was looking for. Countdown logic

3 Answers 3

I have two demos, one with jQuery and one without. Neither use date functions and are about as simple as it gets.

function startTimer(duration, display) < var timer = duration, minutes, seconds; setInterval(function () < minutes = parseInt(timer / 60, 10); seconds = parseInt(timer % 60, 10); minutes = minutes < 10 ? "0" + minutes : minutes; seconds = seconds < 10 ? "0" + seconds : seconds; display.textContent = minutes + ":" + seconds; if (--timer < 0) < timer = duration; >>, 1000); > window.onload = function () < var fiveMinutes = 60 * 5, display = document.querySelector('#time'); startTimer(fiveMinutes, display); >;
 
Registration closes in 05:00 minutes!
function startTimer(duration, display) < var timer = duration, minutes, seconds; setInterval(function () < minutes = parseInt(timer / 60, 10); seconds = parseInt(timer % 60, 10); minutes = minutes < 10 ? "0" + minutes : minutes; seconds = seconds < 10 ? "0" + seconds : seconds; display.text(minutes + ":" + seconds); if (--timer < 0) < timer = duration; >>, 1000); > jQuery(function ($) < var fiveMinutes = 60 * 5, display = $('#time'); startTimer(fiveMinutes, display); >); 

However if you want a more accurate timer that is only slightly more complicated: (version with a start/stop button here)

function startTimer(duration, display) < var start = Date.now(), diff, minutes, seconds; function timer() < // get the number of seconds that have elapsed since // startTimer() was called diff = duration - (((Date.now() - start) / 1000) | 0); // does the same job as parseInt truncates the float minutes = (diff / 60) | 0; seconds = (diff % 60) | 0; minutes = minutes < 10 ? "0" + minutes : minutes; seconds = seconds < 10 ? "0" + seconds : seconds; display.textContent = minutes + ":" + seconds; if (diff >; // we don't want to wait a full second before the timer starts timer(); setInterval(timer, 1000); > window.onload = function () < var fiveMinutes = 60 * 5, display = document.querySelector('#time'); startTimer(fiveMinutes, display); >;
 
Registration closes in minutes!

Now that we have made a few pretty simple timers we can start to think about re-usability and separating concerns. We can do this by asking «what should a count down timer do?»

  • Should a count down timer count down? Yes
  • Should a count down timer know how to display itself on the DOM? No
  • Should a count down timer know to restart itself when it reaches 0? No
  • Should a count down timer provide a way for a client to access how much time is left? Yes
Читайте также:  Write number to file java

So with these things in mind lets write a better (but still very simple) CountDownTimer

function CountDownTimer(duration, granularity) < this.duration = duration; this.granularity = granularity || 1000; this.tickFtns = []; this.running = false; >CountDownTimer.prototype.start = function() < if (this.running) < return; >this.running = true; var start = Date.now(), that = this, diff, obj; (function timer() < diff = that.duration - (((Date.now() - start) / 1000) | 0); if (diff >0) < setTimeout(timer, that.granularity); >else < diff = 0; that.running = false; >obj = CountDownTimer.parse(diff); that.tickFtns.forEach(function(ftn) < ftn.call(this, obj.minutes, obj.seconds); >, that); >()); >; CountDownTimer.prototype.onTick = function(ftn) < if (typeof ftn === 'function') < this.tickFtns.push(ftn); >return this; >; CountDownTimer.prototype.expired = function() < return !this.running; >; CountDownTimer.parse = function(seconds) < return < 'minutes': (seconds / 60) | 0, 'seconds': (seconds % 60) | 0 >; >; 

So why is this implementation better than the others? Here are some examples of what you can do with it. Note that all but the first example can’t be achieved by the startTimer functions.

Источник

Как сделать обратный отчёт времени на JavaScript

В этой статье будет очень интересно, будет рассказываться как сделать JavaScript обратный отсчет времени до даты, при этом мы сделаем не только до дня, а ещё добавим отсчёт времени, плоть до минуты.

Ещё в конце будет можно скачать этот скрипт обратного отсчета времени на javascript для своего сайта, ещё можете посмотреть статью Как сделать таймер на JavaScript, в ней вы сделаете самый обычный таймер, без отсчёта до дней.

HTML:

Для начала, как всегда начнём с HTML, тут всё просто.

Как можете видеть это обычный HTML документ, единственное, мы создаём в нём div элемент, с классом timer , туда будем выводить значение нашего таймера.

JavaScript:

Вот теперь самое главное, это сама логика программы, а точнее теперь делаем скрипт на JavaScript, но сначала посмотрим логику программы.

Читайте также:  Использовать только буквы php

Также, если вы ни разу не работали с временем на JavaScript, то посмотрите этот сайт.

Логика программы:

Суть того, как будет работать наша программа в том, что мы будем брать настоящие время и вычитать его из той даты, до которой нам нужно посмотреть отсчёт, к примеру, дата следующего первая сентября и т.д..

Всё это должно работать в интервале в одну секунду, и так каждый раз программа будет брать настоящие время и вычитать его из конечной даты, пока результат не будет равен или меньше нуля, после таймер останавливается.

Таким образом у нас должен получится таймер на сайт javascript.

Код программы:

Теперь займёмся кодом программы.

Это начало программы, давайте разберём его. Сначала мы создаём переменную которая хранит в себе элемент, в который будем отображать наш отсчёт.

Потом идёт функция в которой будем вычитать время, из заданного нами времени, вычитает настоящие время.

Дальше идёт JSON массив или ассоциативный массив, в котором мы как раз и храним данные до куда нам нужно отсчитывать наш таймер, как можете заметить у меня это девятое Мая, потом создаём строку формата YYYY-MM-DDTHH:mm:ss , но вместо букв подставляем значения из массива.

Сам таймер:

Теперь пришло время сделать сам таймер в интервале.

Теперь разберём код, в начале мы берём настоящие время, потом получаем время до которого нужно сделать отсчёт, дальше вычитаем в нашей функции из назначенного времени, настоящие время, функция возвращает миллисекунды разности этого вычитания.

Проверяем, если миллисекунд меньше или равно нулю, то выключаем интервал и выводим сообщение, что время закончилось.

Если условие не срабатывает, то из разности получаем время, дальше идёт самое интересное, мы создаём строку для вывода таймера, разберём его по подробнее.

  • res.getUTCFullYear() — Получаем год, но в нашем коде вычитаем 1970, это нужно для того, чтобы отсчёт начинался с нулевого года, так как, по умолчанию год начинается 1970 года.
  • res.getUTCMonth() — Просто получаем номер месяца.
  • res.getUTCDate() — Получаем день, но из него вычитаем один, это нужно для того, чтобы не учитывался сегодняшней день, если этого не сделать, то дата всегда будет на один день больше, даже тогда, когда остались считанные минуты.
  • res.getUTCHours() — Получаем час.
  • res.getUTCMinutes() — Получаем минуты.
  • res.getUTCSeconds() — Получаем секунды.
Читайте также:  Javascript call method by string name

Можете заметить что выводим время по UTC. Дальше выводим эту строку таймер.

Тест программы:

Программу мы делать закончили, теперь покажу как она работает. У меня сейчас 23:19, я ставлю время на 23:20.

Источник

how to countdown to a date

I am wondering if anyone can help me. After hours of searching tirelessly on here and the web I can’t seem to find a simple countdown using jquery. I don’t want to use any sort of plugin just a simple jquery code to countdown from a date. I have managed to find this code below. But even with this code placing it in my website nothing appears. I added the jquery file from jquery.com and added the proper divs with counter ID and nothing. If anyone can explain or show me how to make a simple countdown in a function that takes in a date format and returns a countdown I would appreciate the help.

var end = new Date('02/19/2012 10:1 AM'); var _second = 1000; var _minute = _second * 60; var _hour = _minute * 60; var _day = _hour * 24; var timer; function showRemaining() < var now = new Date(); var distance = end - now; if (distance < 0) < clearInterval(timer); document.getElementById('countdown').innerHTML = 'EXPIRED!'; return; >var days = Math.floor(distance / _day); var hours = Math.floor((distance % _day) / _hour); var minutes = Math.floor((distance % _hour) / _minute); var seconds = Math.floor((distance % _minute) / _second); document.getElementById('countdown').innerHTML = days + 'days '; document.getElementById('countdown').innerHTML += hours + 'hrs '; document.getElementById('countdown').innerHTML += minutes + 'mins '; document.getElementById('countdown').innerHTML += seconds + 'secs'; > timer = setInterval(showRemaining, 1000); 

Can you tell me the same question u asked, with dynamic date. U are here giving hardcode date, I want dynamic date

Источник

Оцените статью