Advertisement
ReutenkoIvan

Timer

Jan 3rd, 2020
380
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const days = document.getElementById("days");
  2. const hours = document.getElementById("hours");
  3. const minutes = document.getElementById("minutes");
  4. const seconds = document.getElementById("seconds");
  5. const input = document.getElementById("date");
  6. const show = document.getElementById("show");
  7. let intervalId
  8.  
  9. const getCurrentDate = (from, to) => {
  10.   return {
  11.     remainingDays: Math.floor((from - to) / 1000 / 60 / 60 / 24),
  12.     remainingHours: Math.floor((from - to) / 1000 / 60 / 60 % 24),
  13.     remainingMinutes: Math.floor((from - to) / 1000 / 60 % 60),
  14.     remainingSeconds: Math.floor((from - to) / 1000 % 60),
  15.   }
  16. }
  17.  
  18. const render = (date) => {
  19.   const {
  20.     remainingDays,
  21.     remainingHours,
  22.     remainingMinutes,
  23.     remainingSeconds,
  24.   } = date
  25.  
  26.   days.textContent = remainingDays +" д "
  27.   hours.textContent = remainingHours +" ч "
  28.   minutes.textContent = remainingMinutes +" м "
  29.   seconds.textContent = remainingSeconds +" с "
  30. }
  31.  
  32. const timer = (from) => {
  33.     const to = Date.now()
  34.  
  35.     render(getCurrentDate(from, to))
  36.  
  37.     if (!intervalId) {
  38.      intervalId = setInterval(() => timer(from), 1000);
  39.     }
  40.  
  41.     if(
  42.       Object.values(getCurrentDate(from, to)).every(param => !param)
  43.     ) {
  44.         clearInterval(intervalId)
  45.     }    
  46. }
  47.  
  48. const countdownTimer = () => {
  49.     const target = new Date(input.value)
  50.  
  51.     timer(target)
  52. }
  53.  
  54. input.addEventListener("keydown", (e) => {
  55.     if(e.keyCode < 48 || e.keyCode > 57) {
  56.         e.preventDefault();
  57.     }
  58.     let len = input.value.length
  59.     if(len == 4) {
  60.        
  61.         input.value = input.value + "."
  62.     }
  63.     if(len == 7) {
  64.         input.value = input.value + "."
  65.     }
  66.     if(len == 10) {
  67.         input.value = input.value + " / "
  68.     }
  69.     if(len == 15) {
  70.         input.value = input.value + ":"
  71.     }
  72.     if(len == 18) {
  73.         e.preventDefault();
  74.     }
  75. });
  76.  
  77. show.addEventListener("click", countdownTimer)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement