main.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. //import './styles/counter.css'
  2. import { Countdown } from './counter.js'
  3. import { fetchObject } from './fetch.js';
  4. // select elements
  5. const app = document.querySelector('.countdown-timer');
  6. const message = document.querySelector('.message');
  7. const heading = document.querySelector('h1');
  8. const api = new fetchObject("http://localhost:8000/counter", app.dataset.id);
  9. constcheckCounter();
  10. // Get the new year
  11. const getEndTime = (counter) => {
  12. return new Date(Date.parse(counter.endTime));
  13. };
  14. const format = (t) => {
  15. return t < 10 ? '0' + t : t;
  16. };
  17. const render = (time) => {
  18. app.innerHTML = `
  19. <div class="count-down">
  20. <div class="timer hidden">
  21. <h2 class="days">${format(time.days)}</h2>
  22. <small>Days</small>
  23. </div>
  24. <div class="timer">
  25. <h2 class="hours">${format(time.hours)}</h2>
  26. <small>Hours</small>
  27. </div>
  28. <div class="timer">
  29. <h2 class="minutes">${format(time.minutes)}</h2>
  30. <small>Minutes</small>
  31. </div>
  32. <div class="timer">
  33. <h2 class="seconds">${format(time.seconds)}</h2>
  34. <small>Seconds</small>
  35. </div>
  36. </div>
  37. `;
  38. };
  39. const showMessage = () => {
  40. message.innerHTML = "Le compteur est terminé";
  41. //app.innerHTML = '';
  42. //heading.style.display = 'none';
  43. };
  44. const hideMessage = () => {
  45. message.innerHTML = '';
  46. heading.style.display = 'block';
  47. };
  48. const complete = () => {
  49. showMessage();
  50. constcheckCounter();
  51. };
  52. function constcheckCounter () {
  53. const intervalId = setInterval(async () => {
  54. const counter = await api.getCounter();
  55. heading.innerText = counter.name;
  56. if (counter.state === 'ready') {
  57. hideMessage();
  58. const period = new Date(counter.minutes * 1000 * 60);
  59. render(Countdown.getTime(period));
  60. } else if (counter.state === 'completed') {
  61. const zero = new Date(0);
  62. showMessage();
  63. render(Countdown.getTime(zero));
  64. } else {
  65. clearInterval(intervalId);
  66. const countdownTimer = new Countdown(
  67. getEndTime(counter),
  68. render,
  69. complete
  70. )
  71. }
  72. }, 1000)
  73. }