удалить 0 в таймер обратного отсчета - PullRequest
1 голос
/ 17 июня 2019

Я создал таймер обратного отсчета, который отсчитывает время с 10:00, я хочу, чтобы таймер обратного отсчета удалил первые 0, как только он становится меньше 1 минуты. и включайте конечный ноль, как только его значение меньше 10 секунд.

Например: «0:59» Я хочу удалить 0, поэтому он должен показать «: 59», а затем «: 9» должен показать «: 09»

Честно говоря, я не очень старался .. Я думал, что, возможно, это можно сделать с помощью регулярного выражения, но я не уверен, как.

Мой таймер:

const mins = 10;
// getting the exact time as of the page load
const now = new Date().getTime();
// the math that is done for the actual countdown. So 10*60*1000 + the time retrieved from the page load.
const deadline = mins * 60 * 1000 + now;

// This is a function, however it is a JavaScript method and calls a function.
setInterval(() => {
  // Gets the current time
  var currentTime = new Date().getTime();
  //   gets the 'distance' between the deadline(10 mins) and the current time
  var distance = deadline - currentTime;
  //   found out this method does the math for you, I had to look this up and research it on W3schools
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);
  // Inserts the timer into the Span timer
  timeSpan.innerHTML = minutes + ':' + seconds;
  //   the interval is set to 1 sec, so the timer refreshes and counts down every second

  if (seconds < 0) {
    confirm('Alert For your User!');
    window.location.reload();
  }
}, 1000);

Я ничего не добавил в способ запуска, потому что не уверен, с чего начать! любая помощь будет отличной.

Ответы [ 2 ]

1 голос
/ 17 июня 2019

Ответ:

Вы можете использовать простые операторы if, чтобы изменить вывод непосредственно перед его отображением на экране.

  // check if seconds is single digit
  if(seconds.toString().length === 1) { seconds = "0" + seconds }
  // check if minutes is zero ( which is falsy )
  if(!minutes) minutes = "";
  // Inserts the timer into the Span timer
  timeSpan.innerHTML = minutes + ':' + seconds;

Вы также можете объявить переменную дляудерживать ссылку на interval

// declare the interval as a variable so you can clear it!
let my_interval = setInterval(() => {

Это позволяет очистить его, когда он больше не нужен для запуска:

if (seconds < 0) {
    confirm('Alert For your User!');
    //clear the interval when it finishes!
    clearInterval(my_interval);
  }
}, 1000);

Фрагмент кода:

let timeSpan = document.querySelector("#timeSpan");
const mins = 1;
// getting the exact time as of the page load
const now = new Date().getTime();
// the math that is done for the actual countdown. So 10*60*1000 + the time retrieved from the page load.
const deadline = mins * 60 * 1000 + now;

// This is a function, however it is a JavaScript method and calls a function.

// declare the interval as a variable so you can clear it!
let my_interval = setInterval(() => {
  // Gets the current time
  var currentTime = new Date().getTime();
  //   gets the 'distance' between the deadline(10 mins) and the current time
  var distance = deadline - currentTime;
  //   found out this method does the math for you, I had to look this up and research it on W3schools
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);
  
  // check if seconds is single digit
  if(seconds.toString().length === 1) { seconds = "0" + seconds }
  // check if minutes is zero ( which is falsy )
  if(!minutes) minutes = "";
  // Inserts the timer into the Span timer
  timeSpan.innerHTML = minutes + ':' + seconds;
  
  //   the interval is set to 1 sec, so the timer refreshes and counts down every second

  if (seconds < 0) {
    confirm('Alert For your User!');
    //clear the interval when it finishes!
    clearInterval(my_interval);
  }
}, 1000);
1 голос
/ 17 июня 2019

Вы можете сделать это с помощью некоторых базовых выражений if (см. Ниже), но, как говорили люди в комментариях, выглядит странным, что они читают :59 вместо 0:59

const timeSpan = document.querySelector('#test');
const mins = 10;
// getting the exact time as of the page load
const now = new Date().getTime();
// the math that is done for the actual countdown. So 10*60*1000 + the time retrieved from the page load.
const deadline = 62 * 1000 + now;

// This is a function, however it is a JavaScript method and calls a function.
setInterval(() => {
  // Gets the current time
  var currentTime = new Date().getTime();
  //   gets the 'distance' between the deadline(10 mins) and the current time
  var distance = deadline - currentTime;
  //   found out this method does the math for you, I had to look this up and research it on W3schools
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);

  if (minutes > 0) {
     if(seconds < 10){
            timeSpan.innerHTML = minutes + ':0' + seconds;
      } else {
             // Inserts the timer into the Span timer
             timeSpan.innerHTML = minutes + ':' + seconds;
       }
 
  } else if(seconds < 10) {
   timeSpan.innerHTML = ':0' + seconds;
  } else {
    timeSpan.innerHTML = ':' + seconds;
  }

  //   the interval is set to 1 sec, so the timer refreshes and counts down every second

  if (seconds < 0) {
    confirm('Alert For your User!');
    window.location.reload();
  }
}, 1000);
<p id="test">
</p>
...