Count up timer doesn't work (setInterval part) - javascript

I noticed that the setInterval part makes the code not work. No error is being shown. It works when I manually press the button one at a time.
const stopWatch = document.getElementById("time");
let totalSecs = 0;
const start = document.getElementById("start");
let timeCount = setInterval(seconds, 1000);
let seconds = () => {
start.innerHTML = "Clicked!";
++totalSecs;
let hr = Math.floor(totalSecs / 3600);
let min = Math.floor(totalSecs / 60);
let sec = totalSecs - hr * 3600 - min * 60;
stopWatch.innerHTML = `${hr} : ${min} : ${sec}`;
}
document.addEventListener("click", seconds);
<div id="time">
</div>
<button id="start">Start</button>

Related

How to manipulate input values javascript? / how to use input data js?

Here is app.js of "countdown" project. It works correctly if I declare:
let newLaunch = "1 July 2023" (by typing inside the app.js).
But when I decided to add UI and allow to input date for visitors it does not work! All I've achieved is that correct display console.log of input date (when typing to input field of website) but how can I force my code use this input for correct work of app?
It seems easy but I get stuck. Any helps appreciate.
const daysEl = document.getElementById("days")
const hoursEl = document.getElementById("hours")
const minutesEl = document.getElementById("minutes")
const secondsEl = document.getElementById("seconds")
let newLaunch = "1 July 2023" // It works correctly and can be changed
/* It does not work correctly...
let newLaunch = document.querySelector("input");
newLaunch.addEventListener("input", () => {
console.log(newLaunch.value.split("-").reverse().join("-"));
});
*/
function countdown () {
const newLaunchDate = new Date(newLaunch)
const currentDate = new Date()
const totalSeconds = (newLaunchDate - currentDate) / 1000
const days = Math.floor(totalSeconds / 3600 / 24)
const hours = Math.floor(totalSeconds / 3600) % 24
const minutes = Math.floor(totalSeconds / 60) % 60
const seconds = Math.floor(totalSeconds) % 60
daysEl.innerHTML = days
hoursEl.innerHTML = formatTime(hours)
minutesEl.innerHTML = formatTime(minutes)
secondsEl.innerHTML = formatTime(seconds)
}
const formatTime = time => time < 10 ? `0${time}` : time
//initial call
countdown ()
setInterval(countdown, 1000)
Let's add an input date and work with it. There are many options and some might recommend using library such as "moment.js". But lets keep it simple.
Update: I made some minimal changes so it would work with your example.
const daysEl = document.getElementById("days")
const hoursEl = document.getElementById("hours")
const minutesEl = document.getElementById("minutes")
const secondsEl = document.getElementById("seconds")
var int_id;
const formatTime = time => time < 10 ? `0${time}` : time
function got_date(elem) {
// the parsed value is always formatted yyyy-mm-dd
var str_date = elem.value + 'T00:00'
var newLaunch = str_date;
const newLaunchDate = new Date(newLaunch)
function countdown() {
const currentDate = new Date()
const totalSeconds = (newLaunchDate - currentDate) / 1000
if (totalSeconds < 0) {
console.log("target date has passed");
return;
}
const days = Math.floor(totalSeconds / 3600 / 24)
const hours = Math.floor(totalSeconds / 3600) % 24
const minutes = Math.floor(totalSeconds / 60) % 60
const seconds = Math.floor(totalSeconds) % 60
daysEl.innerHTML = days
hoursEl.innerHTML = formatTime(hours)
minutesEl.innerHTML = formatTime(minutes)
secondsEl.innerHTML = formatTime(seconds)
}
//initial call
countdown()
clearInterval(int_id);
int_id = setInterval(countdown, 1000)
}
<input id="date" type="date" name="date" oninput="got_date(this)">
<hr>
<span id="days"></span>
<span id="hours"></span>
<span id="minutes"></span>
<span id="seconds"></span>

Timer continues after 0

I made a timer for a project in school (I am still in school yes and I do not have JavaScript as a lesson that we get this semester) in JavaScript and it continues after the 0. I got some help from a teacher but I can't reach him with the pandemic and stuff.
This is the code that I wrote and what happens is that when it reaches the date that I put in it goes into -0 -0 -0 -01 and continues from there.
const countdown = () => {
let countDate = new Date('Febuary 9, 2022 00:00:00').getTime();
let now = new Date().getTime();
let gap = countDate - now;
let second = 1000;
let minute = second * 60;
let hour = minute * 60;
let day = hour * 24;
let textDay = Math.floor(gap / day);
let textHour = Math.floor((gap % day) / hour);
let textMinute = Math.floor((gap % hour) / minute);
let textSecond = Math.floor((gap % minute) / second);
document.querySelector('.day').innerText = textDay;
document.querySelector('.hour').innerText = textHour;
document.querySelector('.minute').innerText = textMinute;
document.querySelector('.second').innerText = textSecond;
};
setInterval(countdown, 1000);
setInterval returns a value which you can pass to clearInterval to stop the interval from running. Store that value in a variable, for example:
let countInterval = 0;
const countdown = () => {
//...
};
countInterval = setInterval(countdown, 1000);
Then within countdown you can check if you want to clear that interval. For example, if you want to clear it when gap <= 0 you would perform that logic:
if (gap <= 0) {
clearInterval(countInterval);
return;
}
This would stop the interval from running when that condition is eventually met.
Example:
let countInterval = 0;
const countdown = () => {
let countDate = new Date('January 11, 2022 13:35:00').getTime();
let now = new Date().getTime();
let gap = countDate - now;
if (gap <= 0) {
clearInterval(countInterval);
return;
}
let second = 1000;
let minute = second * 60;
let hour = minute * 60;
let day = hour * 24;
let textDay = Math.floor(gap / day);
let textHour = Math.floor((gap % day) / hour);
let textMinute = Math.floor((gap % hour) / minute);
let textSecond = Math.floor((gap % minute) / second);
document.querySelector('.day').innerText = textDay;
document.querySelector('.hour').innerText = textHour;
document.querySelector('.minute').innerText = textMinute;
document.querySelector('.second').innerText = textSecond;
};
countInterval = setInterval(countdown, 1000);
<div class="day"></div>
<div class="hour"></div>
<div class="minute"></div>
<div class="second"></div>

Countdown Timer Ends Meessage

A few days ago, I created countdown timer by watching a video on YouTube. The countdown timer is completely perfect but one thing is missing from it. When the timer goes to the zero it will hide from the page.
I want to show some text when timer ends. Like if timer goes to zero then timer hides and show this message "You are too late. Stay with us".
This is a .js code in which I need some modification.
const dayDisplay = document.querySelector(".days .number");
const hourDisplay = document.querySelector(".hours .number");
const minuteDisplay = document.querySelector(".minutes .number");
const secondDisplay = document.querySelector(".seconds .number");
const countdownContainer = document.querySelector(".countdown-container");
const endDate = new Date("August 04 2020 10:38:00");
let saleEnded = false;
const updateTimer = () => {
if(countdownContainer) {
let currentDate = new Date();
let difference = endDate.getTime() - currentDate.getTime();
if (difference <= 1000) {
saleEnded = true;
}
const second = 1000;
const minute = second * 60;
const hour = minute * 60;
const day = hour * 24;
let newDay = Math.floor(difference / day);
let newHour = Math.floor((difference % day) / hour);
let newMiute = Math.floor((difference % hour) / minute);
let newSecond = Math.floor((difference % minute) / second);
dayDisplay.innerText = newDay < 10 ? "0" + newDay : newDay;
hourDisplay.innerText = newHour < 10 ? "0" + newHour : newHour;
minuteDisplay.innerText = newMiute < 10 ? "0" + newMiute : newMiute;
secondDisplay.innerText = newSecond < 10 ? "0" + newSecond : newSecond;
};
};
setInterval(() => {
if (!saleEnded) {
updateTimer();
} else {
countdownContainer.style.display = "block";
}
}, 1000);
Try this?
setInterval(() => {
if (!saleEnded) {
updateTimer();
} else {
countdownContainer.style.display = "block";
countdownContainer.innetHTML="You are too late. Stay with us";
}
}, 1000);

Countdown timer using js

Need to create a countdown timer for a online quiz.
Timer should start as soon as user enters web-page.
Tried this piece of code.
<
script >
var fiveMinutes = 3600;
var display = document.getElementById('time');
var myTimer;
function startTime(duration, display) {
var start = Date.now(),
diff,
minutes,
seconds;
function timer() {
diff = duration - (((Date.now() - start) / 1000) | 0);
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 <= 0) {
display.textContent = "TIME IS UP!";
clearInterval(myTimer);
}
};
timer();
myTimer = setInterval(timer, 1000);
}
window.onload = function() {
startTime(fiveMinutes, display);
};
Counting is required not from the current moment, but from the date specified in the startTime variable. Let's consider for your convenience that it has exactly the same format as the return value of Date.now ().
i need to get a variable, give it some value (not Date.now ()), and use it as a starting point
thanks beforehand
Not sure if this is what you are looking for, but this is a simple count down timer that displays the time in the window.
const display = document.getElementById('time');
const fiveminutes = 5 * 60 * 1000;
function timer(endTime) {
var myTimer = setInterval(function() {
let now = new Date().getTime();
let diff = endTime - now;
let minutes = Math.floor(diff % (1000 * 60 * 60) / (1000 * 60));
let seconds = Math.floor(diff % (1000 * 60) / 1000);
minutes = minutes < 10 ? `0${minutes}` : minutes;
seconds = seconds < 10 ? `0${seconds}` : seconds;
display.textContent = minutes + ":" + seconds;
if (diff <= 0) {
display.textContent = "TIME IS UP!";
clearInterval(myTimer);
}
}, 100);
}
window.onload = timer(new Date().getTime() + fiveminutes);
span {
font-family: calibri;
font-size: 4em;
}
<body>
<span id="time"></span>
So I'm not sure if this is what you're looking for. This will trigger when the user enters the page. Your comment is confusing though. Do you want this to start when page loads or at a certain time based on a variable?
window.onload(function() {
setTimeout(function() {
// whatever you want to happen after 3600
// i.e. disable input fields for quiz
}, 3600);
}
This is something I'd been working on that I adapted to try to provide a solution for you here. It's still buggy, but maybe it will give you some ideas, and I'll try to edit it when I have some more time. (I expected to have it working by now but need some rest.)
const
timeInput = document.getElementById("timeInput"),
nowBtn = document.getElementById("nowBtn"),
durationInput = document.getElementById("durationInput"),
confirmBtn = document.getElementById("confirmBtn"),
display = document.getElementById("display");
let
startTime,
timeRemaining,
chronos;
document.addEventListener("click", setUpTimer);
timeInput.addEventListener("focus", ()=>{ nowBtn.checked = false; });
function setUpTimer(event){
// Makes sure the button was the target of the click before proceeding
if(event.target == confirmBtn){
if(nowBtn.checked){ // Puts the current time in the time input
const
clickTime = new Date(),
hours = clickTime.getHours();
let minutes = clickTime.getMinutes();
clickTime.setSeconds(clickTime.getSeconds() + 1);
minutes = minutes < 10 ? "0" + minutes : minutes;
timeInput.value = `${hours}:${minutes}`;
}
const
timeInputValue = timeInput.value,
durationInputValue = durationInput.value;
// Validates input (or complains and aborts)
if(!timeInputValue || !durationInputValue){
display.innerHTML = "Please choose a start time and duration"
clearInterval(chronos);
return;
}
const
startArray = timeInputValue.split(":"),
startHours = parseInt(startArray[0]),
startMinutes = parseInt(startArray[1]),
durationInMinutes = parseInt(durationInput.value),
now = new Date();
// Updates global variables that `countdown` function will need
timeRemaining = durationInMinutes * 60;
startTime = new Date();
startTime.setHours(startHours, startMinutes);
// In case startTime is supposed to be tomorrow
const
nowHrs = now.getHours(),
strtHrs = startTime.getHours()
nowMins = now.getMinutes(),
strtMins = startTime.getMinutes();
// If it looks like the hour already passed, it's probably an earlier hour tomorrow
if(strtHrs < nowHrs || (strtHrs == nowHrs && strtMins < nowMins)){
startTime.setDate(startTime.getDate() + 1);
}
// Announces successful timer setup and resets inputs
const
displayedHours = startTime.getHours(),
storedMinutes = startTime.getMinutes(),
displayedMinutes = storedMinutes < 10 ? "0" + storedMinutes : storedMinutes;
display.innerHTML = `A ${durationInMinutes}-minute timer will start ` + `at ${displayedHours}:${displayedMinutes}`;
timeInput.value = "";
nowBtn.checked = false;
durationInput.value = "5";
// `setInterval` calls `countdown` function every second
console.log(startTime.toLocaleString());
clearInterval(chronos);
chronos = setInterval(countdown, 1000);
}
}
function countdown(){
if(timeRemaining <= 0){
display.innerHTML = "TIME IS UP!";
clearInterval(chronos);
}
else{
const now = new Date();
if(now.getTime() >= startTime.getTime()){
updateDisplayedTime(timeRemaining--);
}
}
}
function updateDisplayedTime(totalSeconds){
let
minutes = Math.floor(totalSeconds / 60),
seconds = totalSeconds % 60;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.innerHTML = `${minutes}:${seconds}`;
}
.inputContainer{ margin-bottom: 1em; }
#display{ font-size: 1.7em;}
#nowBtn {margin-left: 1em; }
<div class="inputContainer">
<label>
<div>Start timer at: </div>
<input type="time" id="timeInput" />
</label>
<label>
<input type ="checkbox" id="nowBtn" />
<span>Now</span>
</label>
</div>
<div class="inputContainer">
<label>
<div>Duration (minutes): </div>
<input type="number" value="5" id="durationInput" min="1" max="1440" />
</label>
</div>
<div class="inputContainer">
<button id="confirmBtn">Confirm</button>
</div>
<div id="display"></div>

start timer when window load

I have some code below which is a forward timer, when I press start it starts counting in hh/mm/ss, and when I press Display time taken it shows time taken in hh/mm/ss inside the tag, and resets the counter to zero on button click and starts counting from zero.
My problem is that the timer initially only starts when I press the start button.
I want to make the timer start automatically when the window loads and remove the start button.
How can be this be achieved?
window.onload = () => {
let hour = 0;
let minute = 0;
let seconds = 0;
let totalSeconds = 0;
let intervalId = null;
function startTimer() {
++totalSeconds;
hour = Math.floor(totalSeconds / 3600);
minute = Math.floor((totalSeconds - hour * 3600) / 60);
seconds = totalSeconds - (hour * 3600 + minute * 60);
document.getElementById("hour").innerHTML = hour;
document.getElementById("minute").innerHTML = minute;
document.getElementById("seconds").innerHTML = seconds;
}
document.getElementById('start-btn').addEventListener('click', () => {
intervalId = setInterval(startTimer, 1000);
})
document.getElementById('Displplaytimetaken').addEventListener('click', () => {
document.getElementById("timetaken").innerHTML = minute + "minutes" + seconds + "seconds";
reset();
});
function reset() {
totalSeconds = 0;
document.getElementById("hour").innerHTML = '0';
document.getElementById("minute").innerHTML = '0';
document.getElementById("seconds").innerHTML = '0';
}
}
<h1 style="font-size:24px;">Time Taken:
<h1 id="timetaken"></h1>
<button id="start-btn">Start</button>
<button id="Displplaytimetaken">Display time taken</button>
window.onload = () => {
let hour = 0;
let minute = 0;
let seconds = 0;
let totalSeconds = 0;
let intervalId = null;
intervalId = setInterval(startTimer, 1000);
function startTimer() {
++totalSeconds;
hour = Math.floor(totalSeconds / 3600);
minute = Math.floor((totalSeconds - hour * 3600) / 60);
seconds = totalSeconds - (hour * 3600 + minute * 60);
document.getElementById("hour").innerHTML = hour;
document.getElementById("minute").innerHTML = minute;
document.getElementById("seconds").innerHTML = seconds;
}
document.getElementById('Displplaytimetaken').addEventListener('click', () => {
document.getElementById("timetaken").innerHTML = minute + "minutes" + seconds + "seconds";
reset();
});
function reset() {
totalSeconds = 0;
document.getElementById("hour").innerHTML = '0';
document.getElementById("minute").innerHTML = '0';
document.getElementById("seconds").innerHTML = '0';
}
}
<h1 style="font-size:24px;">Time Taken:
<h1 id="timetaken">
</h1>
<h2> <span id="hour"></span>
<span id="minute"></span>
<span id="seconds"></span>
</h2>
<button id="Displplaytimetaken">Display time taken</button>
Run it and hope your problem get solved.
Try
<body onload="startTimer()">
In your HTML.
Does that help?

Categories