Я создал таймер обратного отсчета, который ведет обратный отсчет с 10:00, я хочу, чтобы таймер обратного отсчета удалял первый 0, когда он становится меньше 1 минуты. и включите конечный ноль, как только он будет меньше 10 секунд.
Например: «0:59» Я хочу удалить 0, чтобы он отображал «: 59», а затем «: 9» должен отображать «: 09».
Если быть на 100 процентов честным, я мало что пробовал. Я думал, что, возможно, это можно сделать с помощью регулярного выражения, но я не уверен, как это сделать.
Мой таймер:
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);
Я ничего не добавлял для начала, потому что не знаю, с чего начать! любая помощь будет здорово.
Я немного запутался. .9 не .09 - не уверен, что ты имеешь в виду?
@zfrisch - Когда оно меняется с 10 секунд до 9 секунд, например: 10:9, он хочет, чтобы оно читалось как: 10:09.
@TravisJ это для задания, я согласен с вами на 100%, однако, как того хочет инструктор. что касается секунд, которые я хочу читать: 09, :08... и т. д., он говорит добавить 0..



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Вы можете сделать это с помощью некоторых базовых операторов 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>вау .. такой и простой способ сделать это !! ха-ха! если бы мне пришлось добавить это, как бы я это сделал? Я знаю, что это касается метода format()
@ShaunStone Что вы подразумеваете под «добавить это»? | Кроме того, если это решит вашу проблему, отметьте ее как принятую и проголосуйте.
готово :) и мой опыт работы с JavaScript оставляет желать лучшего. Я просто воспользуюсь вашим ответом. и я ценю помощь!
@ShaunStone Просто предупреждаю, мое решение не очень хорошо подходит для кода. Это скорее быстрый способ сделать то, что вы хотите. Есть лучшие способы сделать то, что вы просите, включая создание отдельной функции форматирования.
Вы можете использовать простые операторы 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);Я ценю больше помощи! и я также ценю помощь с последней частью!
@ShaunStone ИМО, это лучший способ сделать это. | Пожалуйста, проголосуйте за оба сообщения, если вы нашли их полезными (нажмите стрелку вверх рядом с ответами).
По сравнению с 0:59, :59 читается плохо, на мой взгляд. Может быть, просто не удалять 0 и двигаться дальше?