start timer when window load - javascript

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?

Related

How to get a timer to end on 0:00 in javascript

I have a timer that counts down from an amount of minutes which a user puts in but now I don't know how to get it to stop once the timer runs out
This is my javascript coding:
function getTime(){
const startingMinutes=prompt("How many minutes is your timer?");
let time=startingMinutes*60;
var overMin=0;
var overSec=00;
const countdownEl=document.getElementById("countdown");
setInterval(updateCountdown, 1000);
function updateCountdown(){
const minutes=Math.floor(time/60);
let seconds= time % 60;
seconds=seconds<10 ? '0' + seconds : seconds;
countdownEl.innerHTML= `${minutes}:${seconds}`;
time--;
if (minutes==0 && seconds==00){
document.getElementById('timesUp').play();
return;
}
}
}
What this ended up doing was playing the timer sound then the timer went backwards when I was trying to get it to stop.
setInterval() returns a timer ID. Use that to cancel it later with clearTimeout():
function getTime() {
const startingMinutes = prompt("How many minutes is your timer?");
let time = Number(startingMinutes) * 60 + 1;
const countdownEl = document.getElementById("countdown");
const timerId = setInterval(updateCountdown, 1000);
function updateCountdown() {
time--;
const minutes = Math.floor(time / 60);
let seconds = time % 60;
countdownEl.innerHTML = minutes + ':' + ('0' + seconds).slice(-2);
if(time <= 0) {
document.getElementById('timesUp').innerHTML = 'Done!';
clearTimeout(timerId);
}
}
}
getTime();
Count down: <span id="countdown"></span>
<div id="timesUp"></div>

Count up timer doesn't work (setInterval part)

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>

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>

how to reset Javascript minute countdown timer

I found this vanilla JS count down timer that really suits my needs.
http://jsfiddle.net/wr1ua0db/17/
`<body>
<div>Registration closes in <span id="time">05:00</span> minutes!</div>
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
window.onload = function () {
var fiveMinutes = 60 * 5,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
I am looking for a reset function that I could assign to buttons or events. I mean a function that would NOT stop the timer... just reset it back to 5:00 ... so it would automatically go to 4:59... 4:58 ... etc
If you move timer variable to parent scope you'll have access to it from other functions. Then you can reset it in a function called resetTimer. See below:
var timer;
function startTimer(duration, display) {
timer = duration;
var minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
function resetTimer() {
timer = 60 * 5;
}
window.onload = function () {
fiveMinutes = 60 * 5,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
Here is a fiddle
Try this one. It starts a timer on load and gives you the ability to reset to the initial state.
<style>
#reset:hover {
cursor: pointer;
}
</style>
<div>Time left = <span id="timer">05:00</span><span id="reset" title="Reset Timer"> ↺</span></div>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
var upgradeTime = 300; // seconds
var seconds = upgradeTime;
function timer() {
var days = Math.floor(seconds / 24 / 60 / 60);
var hoursLeft = Math.floor((seconds) - (days * 86400));
var hours = Math.floor(hoursLeft / 3600);
var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));
var minutes = Math.floor(minutesLeft / 60);
var remainingSeconds = seconds % 60;
function pad(n) {
return (n < 10 ? "0" + n : n);
}
document.getElementById('timer').innerHTML = pad(minutes) + ":" + pad(remainingSeconds);
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('timer').innerHTML = "Completed";
document.getElementById('reset').style.visibility = 'hidden';
} else {
seconds--;
}
}
var countdownTimer = setInterval('timer()', 1000);
// function resetTimer() {
// seconds = upgradeTime;
// }
$("#reset").click(function() {
seconds = upgradeTime;
});
</script>
Use something like addEventListener and call the named function.
(function() {
'use strict';
let reset = document.getElementById('reset');
reset.addEventListener('click', function() {
alert('reset');
//add here the function name to call them.
})
})();
<button id="reset">Reset</buton>

Countdown timer with hundredths?

I'm trying to create a countdown timer in the format of 00:00:00 (minutes, seconds, and hundredths). Right the now the way I set up my countdown timer, is to make sure the user inputs in the format of 00:00:00 (which has to be). From there the countdown time should commence when they click the start button. I see that it does somewhat of a countdown, but I'm not sure what could be the problem with my implementation. The hundredths is not decrementing correctly for some reason. It should start of as 10:00:00 (10 mins) and go to 09:59:99.. 09:59:98, etc.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Countdown Timer</title>
<script type="text/javascript">
var running = 0;
var hundreds = 0;
function validTime() {
var setTime = document.getElementById("timeEntered").value;
var regex = /^\d{2}:\d{2}:\d{2}$/;
if (regex.test(setTime)) {
document.getElementById("timeAlert").innerHTML = "<span class='valid'>Valid</span>";
return (true);
} else {
document.getElementById("timeAlert").innerHTML = "<span class='error'>Invalid time entered. Please make sure it's in the format 00:00:00</span>";
return (false);
}
}
function correctTime(){
if (validTime()){
countdownTimer();
return true;
}else{
alert("Please correct your inputted time.");
return false;
}
}
function countdownTimer() {
var time = document.getElementById("timeEntered").value;
var a = time.split(":");
var timeToSeconds = (+a[0]) * 60 + (+a[1]) * 60 + (+a[2]);
if(parseInt(timeToSeconds) <= 600 ) {
startPause();
}else{
document.getElementById("output").innerHTML = "Sorry. Time range cannot exceed 10 mins.";
}
}
function startPause(){
var time = document.getElementById("timeEntered").value;
var a = time.split(":");
var timeToSeconds = (+a[0]) * 60 + (+a[1]) * 60 + (+a[2]);
if(running == 0){
running = 1;
decrement();
document.getElementById("startPause").innerHTML = "Start/Stop";
}else{
running = 0;
document.getElementById("startPause").innerHTML = "Resume";
}
}
var hundreds = 0;
function decrement(){
var time = document.getElementById("timeEntered").value;
var a = time.split(":");
var timeToSeconds = (+a[0]) * 60 + (+a[1]) * 60 + (+a[2]);
if(running == 1){
var mins = Math.round((timeToSeconds - 30)/60);
var secs = timeToSeconds % 60;
//var hundredths = timeToSeconds % 100;
if(mins < 10) {
mins = "0" + mins;
}
if(secs < 10) {
secs = "0" + secs;
}
document.getElementById("output").innerHTML = mins + ":" + secs + ":" + hundreds;
if (hundreds === 0){
if(timeToSeconds ===0){
clearInterval(countdownTimer);
document.getElementById("output").innerHTML = "Time's Up.";
}else{
timeToSeconds--;
hundreds = 100;
}
}else{
hundreds--;
}
var countdownTimer = setInterval('decrement()', 10)
}
}
</script>
</head>
<body>
<h1>Countdown Timer</h1>
<div id="mainCont">
<p>Please enter the desired time:
<input type="text" id="timeEntered" onblur="validTime();"> <span id="timeAlert"></span>
</p>
<p>
<button id="startPause" onclick="correctTime()">Start/Stop</button>
</p>
<div id="output">00:00:00</div>
</div>
</body>
</html>
I think #bholagabbar's code needs rewriting into hundreths of a second rather than in seconds.
function startTimer(duration, display) {
var timer = duration, minutes, seconds, dispms;
setInterval(function () {
dispms=parseInt(timer % 100,10);
seconds = parseInt(timer / 100, 10);
minutes = parseInt(seconds / 60, 10);
seconds = parseInt(seconds % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
dispms = dispms < 10 ? "0" + dispms : dispms;
display.textContent = minutes + ":" + seconds+":"+dispms;
if (--timer < 0) {
timer = duration;
}
}, 10); //hundreths of a second - 1000 would be 1 second
}
window.onload = function () {
var fiveMinutes = 60 * 5 * 100, //hundreths of second
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
I'm not sure if this is what you wanted but I have some working code for a timer that counts up to the given input (in seconds) which includes the 1/100th of a second. If you want to include ms as you mentioned, you will need 3 0's or ':000' for the display int the end. Here is the code. How will of course, have to mod it for your scenario but the timer is implemented perfe
function startTimer(duration, display) {
var timer = duration, minutes, seconds, dispms;
setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
dispms=parseInt((timer)%100,10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
dispms = dispms < 10 ? "0" + dispms : dispms;
display.textContent = minutes + ":" + seconds+":"+dispms;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
window.onload = function () {
var fiveMinutes = 60 * 5,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
<body>
<div>Registration closes in <span id="time"></span> minutes!</div>
</body>
I think you will have to make changes only in the HTML part. Rest of the logic in my code is fine for a general timer. You will have to pass in the seconds as an argument, that is all

Categories