How to add lap functionality in stopwatch using Javascript? - javascript

I am working on a stopwatch and basically I have all done but I don't know how to add the lapping functionality. I want that as soon as the user clicks on the lap button, a new lap gets added on a "new line". However I am not able to do that here is my code:
let hours = 0;
let minutes = 0;
let seconds = 0;
let miliseconds = 0;
let displayMilisec = miliseconds;
let displaySec = seconds;
let displayMins = minutes;
let displayHours = hours;
let interval = null;
let status = "stopped";
let laps = null;
let lapNow = null;
function start() {
miliseconds++;
if (miliseconds < 10){
displayMilisec = "0" + miliseconds.toString();
}
else {
displayMilisec = miliseconds;
}
if(seconds < 10) {
displaySec = "0" + seconds.toString();
}
else {
displaySec = seconds;
}
if(minutes < 10) {
displayMins = "0" + minutes.toString();
}
else {
displayMins = minutes;
}
if(hours < 10) {
displayHours = "0" + hours.toString();
}
else {
displayHours = hours;
}
if (miliseconds / 100 === 1) {
seconds++;
miliseconds = 0;
if (seconds / 60 === 1) {
minutes++;
seconds = 0;
if (minutes / 60 === 1) {
hours++;
minutes = 0;
}
}
}
document.getElementById("timerMilisec").innerHTML = displayMilisec;
document.getElementById("timerSec").innerHTML = displaySec;
document.getElementById("timerMins").innerHTML = displayMins;
document.getElementById("timerHrs").innerHTML = displayHours;
}
function startStop() {
if (status === "stopped") {
interval = window.setInterval(start, 10);
document.getElementById('startBtn').innerHTML = "Stop";
status = "started";
}
else {
window.clearInterval(interval);
document.getElementById('startBtn').innerHTML = "Start";
status = "stopped";
}
}
function reset() {
window.clearInterval(interval);
miliseconds = 0;
seconds = 0;
minutes = 0;
hours = 0;
document.getElementById("timerMilisec").innerHTML = "00";
document.getElementById("timerSec").innerHTML = "00";
document.getElementById("timerMins").innerHTML = "00";
document.getElementById("timerHrs").innerHTML = "00";
document.getElementById('startBtn').innerHTML = "Start";
status = "stopped";
}
function lap() {
lapNow = hours + " : " + minutes + " : " + seconds + " : " + miliseconds;
laps = document.getElementById('lapRecord').innerHTML + lapNow;
document.getElementById('lapRecord').innerHTML = laps;
}
body {
height: 100vh;
margin: 40px 0px 0px 0px;
background-color: #58e065;
display: flex;
justify-content: center;
overflow: hidden;
}
.display {
display: flex;
left: 50%;
align-items: center;
justify-content: center;
font-family: "nunito","poppins", sans-serif;
font-weight: 700;
font-size: 60px;
color: white;
text-shadow: 3px 3px 0px rgba(150, 150, 150, 1);
}
p {
margin: 5px;
}
.buttons {
display: flex;
justify-content: center;
}
button {
cursor: pointer;
height: 30px;
width: 80px;
border: none;
outline: none;
border-radius: 4px;
background-color: #3b85ed;
font-family: "nunito","poppins", sans-serif;
font-size: 18px;
font-weight: 700;
color: white;
box-shadow: 3px 3px 0px #224f8f;
margin: 4px;
}
button:hover {
background-color: #224f8f;
}
h1 {
position: sticky;
background-color: #ff961d;
display: flex;
justify-content: center;
margin: 30px;
font-family: "nunito", "poppins", sans-serif;
font-size: 40px;
font-weight: 700;
color: white;
text-shadow: 3px 3px 0px rgba(150, 150, 150, 1);
border-radius: 10px;
box-shadow: 3px 3px 0px rgb(179, 101, 0);
}
#header {
width: 100%;
height: 100px;
position: sticky;
}
#laps {
margin-top: 40px;
height: 400px;
scroll-behavior: smooth;
}
<div class="wrapper" id="wrapper">
<div class="display">
<p class="timerDisplay" id="timerHrs">00</p> :
<p class="timerDisplay" id="timerMins">00</p> :
<p class="timerDisplay" id="timerSec">00</p> :
<p class="timerDisplay" id="timerMilisec">00</p>
</div>
<div class="buttons">
<button type="button" id="startBtn" onclick="startStop()">Start</button>
<button type="button" id="resetBtn" onclick="reset()">Reset</button>
<button type="button" id="lapBtn">Lap</button>
</div>
<h1>Laps:</h1>
<div id="laps">
<p id="lapRecord">
</p>
</div>
</div>
I have used a very bad method to do this but yeah I will definitely improve it as soon as know how to add that lap function. I would appreciate an explanation of your code as I just a beginner to coding and I don't know much still. Thank you so much for reading my questions.

Well then, I've edited the code and implemented the lap functionality. Here's what I did.
I would advice you stop using inline html event listeners (onclick). So I replaced all the onclicks with addEventListener('click')
Selecting elements from the DOM is heavy on the performance of your document, so I assigned all the ids to a variable, because these elements were used a lot.
In the lap function, I used template stings to concatenate the time together, and wrapped them in a <div></div> tag with a class of lap in case you want to style the laps later.
I also removed curly braces ({ }) around one-line ifelse statements to reduce the number of lines in the code.
You can test it out here in the snippet. :-)
const lapBtn = document.getElementById('lapBtn');
const timerMilliSec = document.getElementById('timerMilliSec');
const timerSec = document.getElementById('timerSec');
const timerMins = document.getElementById('timerMins');
const timerHrs = document.getElementById('timerHrs');
const startBtn = document.getElementById('startBtn');
const resetBtn = document.getElementById('resetBtn');
const lapRecord = document.getElementById('lapRecord');
let hours = 0;
let minutes = 0;
let seconds = 0;
let miliseconds = 0;
let displayMilisec = miliseconds;
let displaySec = seconds;
let displayMins = minutes;
let displayHours = hours;
let interval = null;
let status = "stopped";
let lapNow = null;
function start() {
miliseconds++;
if (miliseconds < 10) displayMilisec = "0" + miliseconds.toString();
else displayMilisec = miliseconds;
if (seconds < 10) displaySec = "0" + seconds.toString();
else displaySec = seconds;
if (minutes < 10) displayMins = "0" + minutes.toString();
else displayMins = minutes;
if (hours < 10) displayHours = "0" + hours.toString();
else displayHours = hours;
if (miliseconds / 100 === 1) {
seconds++;
miliseconds = 0;
if (seconds / 60 === 1) {
minutes++;
seconds = 0;
if (minutes / 60 === 1) {
hours++;
minutes = 0;
}
}
}
timerMilisec.innerHTML = displayMilisec;
timerSec.innerHTML = displaySec;
timerMins.innerHTML = displayMins;
timerHrs.innerHTML = displayHours;
}
function startStop() {
if (status === "stopped") {
interval = setInterval(start, 10);
startBtn.innerHTML = "Stop";
status = "started";
} else {
clearInterval(interval);
startBtn.innerHTML = "Start";
status = "stopped";
}
}
function reset() {
clearInterval(interval);
miliseconds = 0;
seconds = 0;
minutes = 0;
hours = 0;
timerMilisec.innerHTML = "00";
timerSec.innerHTML = "00";
timerMins.innerHTML = "00";
timerHrs.innerHTML = "00";
startBtn.innerHTML = "Start";
lapRecord.innerHTML = '';
status = "stopped";
}
function lap() {
lapNow = `<div class="lap">${hours} : ${minutes} : ${seconds} : ${miliseconds}</div>`;
lapRecord.innerHTML += lapNow;
}
lapBtn.addEventListener('click', lap);
startBtn.addEventListener('click', startStop);
resetBtn.addEventListener('click', reset);
body {
height: 100vh;
margin: 40px 0px 0px 0px;
background-color: #58e065;
display: flex;
justify-content: center;
overflow: hidden;
}
.display {
display: flex;
left: 50%;
align-items: center;
justify-content: center;
font-family: "nunito", "poppins", sans-serif;
font-weight: 700;
font-size: 60px;
color: white;
text-shadow: 3px 3px 0px rgba(150, 150, 150, 1);
}
p {
margin: 5px;
}
.buttons {
display: flex;
justify-content: center;
}
button {
cursor: pointer;
height: 30px;
width: 80px;
border: none;
outline: none;
border-radius: 4px;
background-color: #3b85ed;
font-family: "nunito", "poppins", sans-serif;
font-size: 18px;
font-weight: 700;
color: white;
box-shadow: 3px 3px 0px #224f8f;
margin: 4px;
}
button:hover {
background-color: #224f8f;
}
h1 {
position: sticky;
background-color: #ff961d;
display: flex;
justify-content: center;
margin: 30px;
font-family: "nunito", "poppins", sans-serif;
font-size: 40px;
font-weight: 700;
color: white;
text-shadow: 3px 3px 0px rgba(150, 150, 150, 1);
border-radius: 10px;
box-shadow: 3px 3px 0px rgb(179, 101, 0);
}
#header {
width: 100%;
height: 100px;
position: sticky;
}
#laps {
margin-top: 40px;
height: 400px;
scroll-behavior: smooth;
}
<div class="wrapper" id="wrapper">
<div class="display">
<p class="timerDisplay" id="timerHrs">00</p> :
<p class="timerDisplay" id="timerMins">00</p> :
<p class="timerDisplay" id="timerSec">00</p> :
<p class="timerDisplay" id="timerMilisec">00</p>
</div>
<div class="buttons">
<button type="button" id="startBtn">Start</button>
<button type="button" id="resetBtn">Reset</button>
<button type="button" id="lapBtn">Lap</button>
</div>
<h1>Laps:</h1>
<div id="laps">
<p id="lapRecord"></p>
</div>
</div>

Related

Can the progress bar go according to the real time throughout the day?

I have my site under construction.
This will last 1 day, from 00:00 to 23:59.
I would like the progress bar to go according to the time throughout the day.
For example:
If the time is 06:00 the bar should show 25%
if it's 12:00 it shows 50%,
if it is 18:00 it should show 75%.
However, if it is 18:15, it should show the percentage in detail, for example 75.8%.
Is it possible for it to happen and work throughout the day? Thanks
function checkTime(){
var today = new Date();
var hr = today.getHours();
var min = today.getMinutes();
var sec = today.getSeconds();
var hours = document.querySelector(".hours");
var minutes = document.querySelector(".minutes");
var seconds = document.querySelector(".seconds");
if(hr < 10){
hr = "0" + hr;
}
if(min < 10){
min = "0" + min;
}
if(sec < 10){
sec = "0" + sec;
}
hours.textContent = hr + " : ";
minutes.textContent = min + " : ";
seconds.textContent = sec;
}
setInterval(checkTime, 500);
const progress = document.querySelector('.progress')
const percentage = document.querySelector('.progress span')
let per = 0;
function progressLoad(){
if(per>=35){
progress.style.width = `35%`;
percentage.innerHTML = "35%"
}else{
progress.style.width = `${per}%`;
percentage.innerHTML = `${per}%`;
}
per++
}
setInterval(progressLoad,90)
.bg {background:#08093cb3;}
.hours, .minutes, .seconds {
float: left;
font-size: 1.5em;
color: #008c8c;
}
.progress-wrapper {
width: 100%;
background: #222;
display: flex;
margin-bottom: 20px;
border-radius: 5px;
}
.progress {
width: 0%;
height: 10px;
background: green;
border-radius: 5px;
display: flex;
justify-content: flex-end;
}
.progress span {
color: white;
position: relative;
top: 13px;
left: 25px;
font-weight: 800;
}
<body class="bg">
<div class="hours"></div>
<div class="minutes"></div>
<div class="seconds"></div>
<br><br>
<div class="progress-wrapper">
<div class="progress">
<span>0%</span>
</div>
</div>
</body>
Simply calculate the percentage of day in checkTime()
pc = Math.round(((hr * 60 * 60 + min * 60 + sec) / (24 * 60 * 60)) * 1000) / 10;
let pc,
per = 0;
function checkTime() {
var today = new Date();
var t = [today.getHours(), today.getMinutes(), today.getSeconds()];
pc = Math.round(((t[0] * 60 * 60 + t[1] * 60 + t[2]) / (24 * 60 * 60)) * 1000) / 10;
document.querySelector(".time").textContent = t.map((d) => (d < 10 ? "0" + d : d)).join(" : ");
}
function progressLoad() {
document.querySelector(".progress").style.width = `${per >= pc ? pc : per}%`;
document.querySelector(".progress span").innerHTML = `${per >= pc ? pc : per}%`;
per++;
}
checkTime();
setInterval(checkTime, 500);
setInterval(progressLoad, 90);
.bg {
background: #08093cb3;
}
.time {
float: left;
font-size: 1.5em;
color: #008c8c;
}
.progress-wrapper {
width: 100%;
background: #222;
display: flex;
margin-bottom: 20px;
border-radius: 5px;
}
.progress {
width: 0%;
height: 10px;
background: green;
border-radius: 5px;
display: flex;
justify-content: flex-end;
}
.progress span {
color: white;
position: relative;
top: 13px;
left: 25px;
font-weight: 800;
}
<body class="bg">
<div class="time"></div>
<br><br>
<div class="progress-wrapper">
<div class="progress">
<span>0%</span>
</div>
</div>
</body>
Just Divide the total seconds elapsed by total seconds in a day to get the percentage...
// to calculate time elapsed
// variables defined outside the function
var today = new Date();
var hr = today.getHours();
var min = today.getMinutes();
var sec = today.getSeconds();
function checkTime(){
hr = today.getHours();
min = today.getMinutes();
sec = today.getSeconds();
var hours = document.querySelector(".hours");
var minutes = document.querySelector(".minutes");
var seconds = document.querySelector(".seconds");
if(hr < 10){
hr = "0" + hr;
}
if(min < 10){
min = "0" + min;
}
if(sec < 10){
sec = "0" + sec;
}
hours.textContent = hr + " : ";
minutes.textContent = min + " : ";
seconds.textContent = sec;
}
setInterval(checkTime, 500);
const progress = document.querySelector('.progress')
const percentage = document.querySelector('.progress span')
function progressLoad(){
let timeElapsed = hr*60*60 + min*60 + sec
let per =
parseInt(timeElapsed*100/(24*60*60));
/*
if(per>=35){
progress.style.width = `35%`;
percentage.innerHTML = "35%"
}else{
progress.style.width = `${per}%`;
percentage.innerHTML = `${per}%`;
}
per++
*/
progress.style.width = `${per}%`;
percentage.innerHTML = `${per}%`;
}
setInterval(progressLoad,90)
.bg {background:#08093cb3;}
.hours, .minutes, .seconds {
float: left;
font-size: 1.5em;
color: #008c8c;
}
.progress-wrapper {
width: 100%;
background: #222;
display: flex;
margin-bottom: 20px;
border-radius: 5px;
}
.progress {
width: 0%;
height: 10px;
background: green;
border-radius: 5px;
display: flex;
justify-content: flex-end;
}
.progress span {
color: white;
position: relative;
top: 13px;
left: 25px;
font-weight: 800;
}
<body class="bg">
<div class="hours"></div>
<div class="minutes"></div>
<div class="seconds"></div>
<br><br>
<div class="progress-wrapper">
<div class="progress">
<span>0%</span>
</div>
</div>
</body>

Enable Button when click counter is at 100 with jQuery/JavaScript

I've been doing a little game lately. You have two buttons with which you can earn money, One has a timer and when the timer is over you can click on it and you get +$500 in your account.
With the other button you can earn money by clicking on it. With every click you get +1$ in your account.
Now I wanted to make a button that doubles the money. For this I made a third button that says "Enable me".
I wanted to make a function that enables the button when your account is over $100. Do you know how I could do it?
Here is my code:
$(".addOneButton").click(function() {
setCounter(getCounter() + 1);
});
function myFunction(){
$(".addOneButton").click(function() {
setCounter(getCounter() + 1);
});
}
function hideUpgradeButton() {
document.getElementById("upgrade").style.display = "none";
}
$('#btn').prop('disabled',true);
startCountDown();
function getCounter(){
return parseInt($('#counter').html());
}
function setCounter(count) {
$('#counter').html(count);
}
$("#btn").click(function() {
setCounter(getCounter() + 500);
$('#btn').prop('disabled',true);
startCountDown();
});
function startCountDown() {
var counter = document.getElementById("counter")
var minutes = 1,
seconds = 30;
$("#countdown").html(minutes + ":" + seconds);
var count = setInterval(function() {
if (parseInt(minutes) < 0 || parseInt(seconds) <=0 ) {
$("#countdown").html("Collect" + " <i class=\"bi bi-unlock-fill\"></i>");
clearInterval(count);
$('#btn').prop('disabled',false);
} else {
$("#countdown").html(minutes + ":" + seconds + " <i class=\"bi bi-lock-fill\"></i>");
seconds--;
if (seconds < 10) seconds = "0" + seconds;
}
if(parseInt(minutes) === 1 && parseInt(seconds) === 0) {
minutes = 0;
seconds = 60
}
if(parseInt(counter) > 500){
$("#upgrade").prop('disabled', false);
}
}, 1000);
}
* {
font-family: 'Roboto', sans-serif;
}
#total {
display: flex;
justify-content: center;
margin: 0 auto;
width: auto;
}
#border {
border: 1px solid grey;
padding: 0.2em 1em 0.2em 1em;
}
.inline {
display: inline-block;
}
/*
Timer Button Start
*/
button:disabled {
font-size: 25px;
width: 200px;
padding: 0.2em;
background: #f54532;
color: #d0d0d0;
border: none;
border-radius: 5px;
cursor: pointer;
transition: all 0.3s;
filter: grayscale(30%);
}
button {
font-size: 25px;
width: 200px;
padding: 0.2em;
background: #f54532;
color: #fff;
border: none;
border-radius: 5px;
cursor: pointer;
transition: all 0.3s;
margin: 0.5em;
user-select: none;
}
button:enabled:hover {
transform: scale(1.1);
}
button:enabled:active {
transform: scale(0.9);
filter: brightness(70%);
}
/*
Timer Button End
*/
.bi {
font-size: 20px;
display: inline-flex;
align-items: center;
}
#centerButtons {
display: flex;
justify-content: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link href='http://fonts.googleapis.com/css?family=Roboto&subset=latin,greek,greek-ext,latin-ext,cyrillic' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons#1.3.0/font/bootstrap-icons.css">
<div id="total">
<div id="border">
<div class="inline" id="counter">0</div>
<div class="inline" id="money">$</div>
</div>
</div><br>
<div id="centerButtons">
<button id="btn">
<span id="countdown">Collect</span>
</button>
<button class="addOneButton" onclick="setCounter()">Add One!</button>
</div>
<button id="upgrade" onclick="myFunction(); hideUpgradeButton()" disabled>Enable me!</button>
Set a variable that holds the increment value , and a var that make sur you enable the button double once ,
then check if counter > 100 && wasn't enabled yet then increment the increment using the function myFunction()
PS I've edited timer value : to go fast with testing :
see below, snippet :
var increment = 1;
var enabled = false;
$(".addOneButton").click(function() {
var count = getCounter();
if(count > 100 && !enabled) {
$("#upgrade").prop('disabled', false)
enabled = true;
}
setCounter(count + increment);
});
function myFunction() {
increment++;
}
function hideUpgradeButton() {
document.getElementById("upgrade").style.display = "none";
}
$('#btn').prop('disabled', true);
startCountDown();
function getCounter() {
return parseInt($('#counter').html());
}
function setCounter(count) {
$('#counter').html(count);
}
$("#btn").click(function() {
setCounter(getCounter() + 500);
$('#btn').prop('disabled', true);
startCountDown();
});
function startCountDown() {
var counter = document.getElementById("counter")
var minutes = 0,
seconds = 10
$("#countdown").html(minutes + ":" + seconds);
var count = setInterval(function() {
if (parseInt(minutes) < 0 || parseInt(seconds) <= 0) {
$("#countdown").html("Collect" + " <i class=\"bi bi-unlock-fill\"></i>");
clearInterval(count);
$('#btn').prop('disabled', false);
} else {
$("#countdown").html(minutes + ":" + seconds + " <i class=\"bi bi-lock-fill\"></i>");
seconds--;
if (seconds < 10) seconds = "0" + seconds;
}
if (parseInt(minutes) === 1 && parseInt(seconds) === 0) {
minutes = 0;
seconds = 60
}
if (parseInt(counter) > 500) {
$("#upgrade").prop('disabled', false);
}
}, 1000);
}
* {
font-family: 'Roboto', sans-serif;
}
#total {
display: flex;
justify-content: center;
margin: 0 auto;
width: auto;
}
#border {
border: 1px solid grey;
padding: 0.2em 1em 0.2em 1em;
}
.inline {
display: inline-block;
}
/*
Timer Button Start
*/
button:disabled {
font-size: 25px;
width: 200px;
padding: 0.2em;
background: #f54532;
color: #d0d0d0;
border: none;
border-radius: 5px;
cursor: pointer;
transition: all 0.3s;
filter: grayscale(30%);
}
button {
font-size: 25px;
width: 200px;
padding: 0.2em;
background: #f54532;
color: #fff;
border: none;
border-radius: 5px;
cursor: pointer;
transition: all 0.3s;
margin: 0.5em;
user-select: none;
}
button:enabled:hover {
transform: scale(1.1);
}
button:enabled:active {
transform: scale(0.9);
filter: brightness(70%);
}
/*
Timer Button End
*/
.bi {
font-size: 20px;
display: inline-flex;
align-items: center;
}
#centerButtons {
display: flex;
justify-content: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link href='http://fonts.googleapis.com/css?family=Roboto&subset=latin,greek,greek-ext,latin-ext,cyrillic' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons#1.3.0/font/bootstrap-icons.css">
<div id="total">
<div id="border">
<div class="inline" id="counter">0</div>
<div class="inline" id="money">$</div>
</div>
</div><br>
<div id="centerButtons">
<button id="btn">
<span id="countdown">Collect</span>
</button>
<button class="addOneButton" onclick="setCounter()">Add One!</button>
</div>
<button id="upgrade" onclick="myFunction(); hideUpgradeButton()" disabled>Enable me!</button>
change getCounter:
function getCounter(){
var counter = parseInt($('#counter').html());
if(parseInt(counter) > 99){
$("#upgrade").prop('disabled', false);
}
return counter;
}

CSS Animation not clearing in JS

I'm penning a digital clock and I want to create a feature that slides the numbers up on change. I'm applying inline animation to the secondDiv and clearing it every second, but the animation only shows up on page load. I want it to show every second, hence trying to clear it first. I've tried secondDiv.style.animation = "" as well as secondDiv.removeAttribute('style'), but to no avail.
Codepen Example
JS
const clock = document.querySelector("#clock-body");
const hourDiv = document.querySelector("#hours");
const minuteDiv = document.querySelector("#minutes");
const secondDiv = document.querySelector("#seconds");
const zone = document.querySelector("#zone");
const getDate = () => {
let date = new Date();
let hours = date.getHours();
let minutes = date.getMinutes();
let seconds = date.getSeconds();
if (hours > 12) {
hours = hours - 12;
}
if (minutes < 10) {
minutes = `0${minutes}`;
}
if (seconds < 10) {
seconds = `0${seconds}`;
}
hourDiv.textContent = hours;
minuteDiv.textContent = minutes;
secondDiv.textContent = seconds;
secondDiv.style.animation = `0.3s change`;
};
window.setInterval(getDate, 1000);
CSS
#keyframes change {
0% {
transform: translateY(0);
}
100% {
transform: translateY(-30px);
}
}
What am I doing wrong? How can I clear the Inline Animation every second before it's applied again?
Remove style just after animation is finished with help of animationend event. Without waiting for next loop.
Instead of:
secondDiv.removeAttribute("style");
Use
secondDiv.addEventListener('animationend', () => {
secondDiv.removeAttribute("style");
});
outside your getDate function
Full example
const clock = document.querySelector("#clock-body");
const hourDiv = document.querySelector("#hours");
const minuteDiv = document.querySelector("#minutes");
const secondDiv = document.querySelector("#seconds");
const zone = document.querySelector("#zone");
const getDate = () => {
let date = new Date();
let hours = date.getHours();
let minutes = date.getMinutes();
let seconds = date.getSeconds();
if (hours > 12) {
hours = hours - 12;
}
if (minutes < 10) {
minutes = `0${minutes}`;
}
if (seconds < 10) {
seconds = `0${seconds}`;
}
hourDiv.textContent = hours;
minuteDiv.textContent = minutes;
secondDiv.textContent = seconds;
secondDiv.style.animation = `0.3s change`;
};
secondDiv.addEventListener('animationend', () => {
secondDiv.removeAttribute("style");
});
window.setInterval(getDate, 1000);
body {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background: linear-gradient(#444, #222);
height: 100vh;
color: #fff;
}
#clock-body {
display: flex;
align-items: center;
font-size: 2rem;
font-family: "Courier New", Courier, monospace;
padding: 2.5rem;
border: 10px solid #fff;
border-radius: 20px;
background: #000;
box-shadow: 0 8px 30px #212121;
span {
font-weight: 300;
font-size: 3rem;
}
#hours,
#minutes,
#seconds {
font-weight: 700;
font-size: 4rem;
border-radius: 3px;
}
}
#keyframes change {
0% {
transform: translateY(0);
}
100% {
transform: translateY(-30px);
}
}
<div id="clock-body">
<div id="hours"></div>
<span>:</span>
<div id="minutes"></div>
<span>:</span>
<div id="seconds"></div>
<div id="zone"></div>
</div>
Here is my solution, Its not perfect, but it can be a good starting point.
I am using setTimeout inside the function along with transition property of css to control the position and opacity of the number
const clock = document.querySelector("#clock-body");
const hourDiv = document.querySelector("#hours");
const minuteDiv = document.querySelector("#minutes");
const secondDiv = document.querySelector("#seconds");
const zone = document.querySelector("#zone");
const getDate = () => {
// secondDiv.removeAttribute("style");
secondDiv.style.transition = `opacity 0.3s linear`;
secondDiv.style.transform = `translateY(0px)`;
secondDiv.style.opacity = `1`;
let date = new Date();
let hours = date.getHours();
let minutes = date.getMinutes();
let seconds = date.getSeconds();
if (hours > 12) {
hours = hours - 12;
}
if (minutes < 10) {
minutes = `0${minutes}`;
}
if (seconds < 10) {
seconds = `0${seconds}`;
}
hourDiv.textContent = hours;
minuteDiv.textContent = minutes;
secondDiv.textContent = seconds;
setTimeout(() => {
secondDiv.style.transition = `all 0.3s linear`;
secondDiv.style.transform = `translateY(-50px)`;
secondDiv.style.opacity = `0`;
}, 500);
};
window.setInterval(getDate, 1000);
body {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background: linear-gradient(#444, #222);
height: 100vh;
color: #fff;
}
#clock-body {
display: flex;
align-items: center;
font-size: 2rem;
font-family: "Courier New", Courier, monospace;
padding: 2.5rem;
border: 10px solid #fff;
border-radius: 20px;
background: #000;
box-shadow: 0 8px 30px #212121;
}
#clock-body span {
font-weight: 300;
font-size: 3rem;
}
#clock-body #hours,
#clock-body #minutes,
#clock-body #seconds {
font-weight: 700;
font-size: 4rem;
border-radius: 3px;
}
#keyframes change {
0% {
transform: translateY(0);
}
100% {
transform: translateY(-30px);
}
}
<div id="clock-body">
<div id="hours"></div>
<span>:</span>
<div id="minutes"></div>
<span>:</span>
<div class="s-div" id="seconds"></div>
<div id="zone"></div>
</div>

JavaScript Beep Sound incorrect on mobile but desktop

I creat short script want to make a beep sound every second.
It just a simple JS in HTML file.
When it run on desktop (chrome) it working (beep every sec) but when it run on mobile (both android and ios) it only beep once and gone.
Can anyone suggest a fix?
I try many method but cannot find a fix.
here is script
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
* {
box-sizing: border-box;
}
body {
font-family: Arial;
margin: 0 !important;
padding: 0 !important;
}
h1 {
margin-top: 1px;
margin-bottom: 1px;
margin-right: 1px;
margin-left: 1px;
}
input[type=text], select, textarea{
width: 100%;
padding: 12px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
resize: vertical;
}
label {
padding: 15px 2px 2px 5px;
display: inline-block;
}
select.form-control{display:inline-block}
.button {
background-color: #4CAF50; /* Green */
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
}
.button:hover {
background-color: #45a049;
}
table, th, td {
border: 0px;
padding:0;
margin:0;
border-collapse: collapse;
}
td {
border: 0px;
padding:1;
margin:0;
}
</style>
<script>
var bit = 18;
var flat = 1;
var cmd = [0,0,0,0,0,0,0,0,0,0,0,0,0];
var j = 0;
var secTime = 0;
var t;
var confirmCmd;
var beep = function () {
(new
Audio(
"data:audio/wav;base64,//uQRAAAAWMSLwUIYAAsYkXgoQwAEaYLWfkWgAI0wWs/ItAAAGDgYtAgAyN+QWaAAihwMWm4G8QQRDiMcCBcH3Cc+CDv/7xA4Tvh9Rz/y8QADBwMWgQAZG/ILNAARQ4GLTcDeIIIhxGOBAuD7hOfBB3/94gcJ3w+o5/5eIAIAAAVwWgQAVQ2ORaIQwEMAJiDg95G4nQL7mQVWI6GwRcfsZAcsKkJvxgxEjzFUgfHoSQ9Qq7KNwqHwuB13MA4a1q/DmBrHgPcmjiGoh//EwC5nGPEmS4RcfkVKOhJf+WOgoxJclFz3kgn//dBA+ya1GhurNn8zb//9NNutNuhz31f////9vt///z+IdAEAAAK4LQIAKobHItEIYCGAExBwe8jcToF9zIKrEdDYIuP2MgOWFSE34wYiR5iqQPj0JIeoVdlG4VD4XA67mAcNa1fhzA1jwHuTRxDUQ//iYBczjHiTJcIuPyKlHQkv/LHQUYkuSi57yQT//uggfZNajQ3Vmz+ Zt//+mm3Wm3Q576v////+32///5/EOgAAADVghQAAAAA//uQZAUAB1WI0PZugAAAAAoQwAAAEk3nRd2qAAAAACiDgAAAAAAABCqEEQRLCgwpBGMlJkIz8jKhGvj4k6jzRnqasNKIeoh5gI7BJaC1A1AoNBjJgbyApVS4IDlZgDU5WUAxEKDNmmALHzZp0Fkz1FMTmGFl1FMEyodIavcCAUHDWrKAIA4aa2oCgILEBupZgHvAhEBcZ6joQBxS76AgccrFlczBvKLC0QI2cBoCFvfTDAo7eoOQInqDPBtvrDEZBNYN5xwNwxQRfw8ZQ5wQVLvO8OYU+mHvFLlDh05Mdg7BT6YrRPpCBznMB2r//xKJjyyOh+cImr2/4doscwD6neZjuZR4AgAABYAAAABy1xcdQtxYBYYZdifkUDgzzXaXn98Z0oi9ILU5mBjFANmRwlVJ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OIAyDvEyG8S5yfK6dhZc0Tx1KI/gviKL6qvvFs1+bWtaz58uUNnryq6kt5RzOCkPWlVqVX2a/EEBUdU1KrXLf40GoiiFXK///qpoiDXrOgqDR38JB0bw7SoL+ZB9o1RCkQjQ2CBYZKd/+VJxZRRZlqSkKiws0WFxUyCwsKiMy7hUVFhIaCrNQsKkTIsLivwKKigsj8XYlwt/WKi2N4d//uQRCSAAjURNIHpMZBGYiaQPSYyAAABLAAAAAAAACWAAAAApUF/Mg+0aohSIRobBAsMlO//Kk4soosy1JSFRYWaLC4qZBYWFRGZdwqKiwkNBVmoWFSJkWFxX4FFRQWR+LsS4W/rFRb//////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////VEFHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAU291bmRib3kuZGUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMjAwNGh0dHA6Ly93d3cuc291bmRib3kuZGUAAAAAAAAAACU="
)).play();
}
function clock () {
var h1 = document.getElementById('clockShow'),
seconds = 0, minutes = 0, hours = 0;
function add() {
seconds++;
secTime++
if (seconds >= 60) {
seconds = 0;
minutes++;
if (minutes >= 60) {
minutes = 0;
hours++;
}
}
h1.textContent = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);
timer();
beep();
}
function timer() {
t = setTimeout(add, 1000);
}
/* Start button */
start.onclick = function () {
//init
document.getElementById("msg").innerHTML="UP";
document.getElementById("start").disabled = true;
timer();
}
/* Clear button */
clear.onclick = function() {
clearTimeout(t);
h1.textContent = "00:00:00";
seconds = 0; minutes = 0; hours = 0;
document.getElementById("msg").innerHTML="START";
j = 0;
secTime = 0;
document.getElementById("Next").innerHTML = "Count Down";
document.getElementById("start").disabled = false;
}
}
</script>
</head>
<body onload="clock()">
<div align="center">
<h1 id="msg" style="font-size:20vw">START</h1>
<span style="font-size:5vw" id="Next">Clock</span>
</div><br>
<div align="center">
<h1 id="clockShow" style="font-size:5vw"><time>00:00:00</time></h1>
<button id="start" class="button">Start</button>
<button id="clear" class="button">Abort</button>
</div>
</body>
</html>

How do I execute a function after a setInterval function finishes jQuery

I'm building a 'Pomodoro Clock' and I've managed to make the time and the break, and I want to switch between the TIME and the BREAK.
I want to know how to call the breakTime after the time goes to '0' and call back the time function when the break time goes to '0'.
This is my code: (EDIT)
$(document).ready(function() {
// TIMERS AND BREAKERS
$('.resetWrapper').hide();
var timeBtn = false;
var breakBtn = false;
var timeMin = parseInt($('#timeMin').text());
var breakMin = parseInt($('#timeMin').text());
// Reset Buttons
$('#timeReset').click(function() {
timeBtn = false;
timeMin = 5;
$('#timeMin').html('5');
$('#timeResetWrapper').slideUp();
});
$('#breakReset').click(function() {
breakBtn = false;
breakMin = 5;
$('#breakMin').html('5');
$('#breakResetWrapper').slideUp();
});
// Plus and minus TIME buttons
$('#plusTimeMin').click(function() {
if (timeMin >= 1) {
timeMin += 1;
$('#timeMin').html(timeMin);
}
if (!timeBtn) {
timeBtn = true;
$('#timeResetWrapper').slideDown();
}
});
$('#minusTimeMin').click(function() {
if (timeMin > 1) {
timeMin -= 1;
$('#timeMin').html(timeMin);
}
if (!timeBtn) {
timeBtn = true;
$('#timeResetWrapper').slideDown();
}
});
// Plus and minus BREAK buttons
$('#plusBreakMin').click(function() {
if (breakMin >= 1) {
breakMin += 1;
$('#breakMin').html(breakMin);
}
if (!breakBtn) {
breakBtn = true;
$('#breakResetWrapper').slideDown();
}
});
$('#minusBreakMin').click(function() {
if (breakMin > 1) {
breakMin -= 1;
$('#breakMin').html(breakMin);
}
if (!breakBtn) {
breakBtn = true;
$('#breakResetWrapper').slideDown();
}
});
// FINISH TIMERS AND BREAKERS /// ------------->
// POMODORO TIMES /// ------------->
var secs = 60;
var startInterval;
var breakInterval;
$("#playPomodoro").click(function() {
a = true;
secs = 60;
timeMin = parseInt($('#timeMin').text()) - 1;
breakMin = parseInt($('#breakMin').text()) - 1;
clearInterval(startInterval);
startInterval = setInterval(time, 100);
});
function time() {
if (timeMin >= 0 && timeMin < 10) {
if (secs > 0) {
if (secs <= 10) {
$("#pomodoroTime").html("0" + timeMin + " : 0" + (secs - 1));
secs -= 1;
} else {
$("#pomodoroTime").html("0" + timeMin + " : " + (secs - 1));
secs -= 1;
}
} else if (secs === 0) {
timeMin -= 1;
secs = 60;
}
} else {
if (secs > 0) {
if (secs <= 10) {
$("#pomodoroTime").html(timeMin + " : 0" + (secs - 1));
secs -= 1;
} else {
$("#pomodoroTime").html(timeMin + " : " + (secs - 1));
secs -= 1;
}
} else if (secs === 0) {
timeMin -= 1;
secs = 60;
}
}
}
function breakTime() {
if (breakMin >= 0 && breakMin < 10) {
if (secs > 0) {
if (secs <= 10) {
$("#pomodoroTime").html("0" + breakMin + " : 0" + (secs - 1));
secs -= 1;
} else {
$("#pomodoroTime").html("0" + breakMin + " : " + (secs - 1));
secs -= 1;
}
} else if (secs === 0) {
breakMin -= 1;
secs = 60;
}
} else {
if (secs > 0) {
if (secs <= 10) {
$("#pomodoroTime").html(breakMin + " : 0" + (secs - 1));
secs -= 1;
} else {
$("#pomodoroTime").html(breakMin + " : " + (secs - 1));
secs -= 1;
}
} else if (secs === 0) {
breakMin -= 1;
secs = 60;
}
}
}
// FINISH POMODORO TIMES //// ------------->
});
body {
background: rgba(50, 101, 115, 1.0);
font-family: 'Open Sans', sans-serif!important;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
.row {
margin-top: 50px;
}
.times {
color: white;
text-align: center;
}
.timesContainer {
background: rgba(0, 0, 0, 0.3);
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 4px;
padding: 12px 0px 15px 0px;
}
.title {
margin-top: 40px;
text-decoration: underline;
color: rgba(255, 255, 255, 1.0);
font-size: 2.5em;
text-align: center;
}
.number {
margin-right: 10px;
margin-left: 10px;
}
.plusbtn:hover,
.plusbtn:active,
.plusbtn:target,
.minusbtn:hover,
.minusbtn:active,
.minusbtn:target {
background: none;
color: gray;
transform: rotate(360deg);
font-size: 20px;
outline: none;
border: none;
}
.plusbtn,
.minusbtn {
font-size: 20px;
color: white;
background: none;
border: none;
transition: all 1s;
outline: none;
}
.pomodoroContainer {
margin-top: 50px;
text-align: center;
vertical-align: middle;
}
.pomodoro {
display: inline-block;
height: 350px;
width: 350px;
background: none;
border: 3px solid black;
border-radius: 50%;
vertical-align: middle;
}
#pomodoroTime {
font-size: 50px;
vertical-align: middle;
margin-top: 38%;
color: white;
}
.playStop {
font-size: 50px;
margin-top: 10px;
text-align: center;
}
#playPomodoro {
color: #77A9B7;
}
#stopPomodoro {
color: #E8574B;
}
.resetBtn {
margin-top: 10px;
background: rgba(0, 0, 0, 0.3);
padding: 10px;
border-radius: 5px;
border: none;
outline: none;
width: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<body>
<div class="container-fluid">
<div class="title">
Pomodoro Clock
</div>
<div class="row">
<div class="times col-xs-6">
<div class="timesContainer">
<h4> Time in minutes </h4>
<button id="plusTimeMin" class="plusbtn">+</button>
<span id="timeMin" class="number">5</span>
<button id="minusTimeMin" class="minusbtn">-</button>
<br>
<div id="timeResetWrapper" class="resetWrapper">
<button id="timeReset" class="resetBtn">Reset</button>
</div>
</div>
</div>
<div class="times col-xs-6">
<div class="timesContainer">
<h4> Break in minutes </h4>
<button id="plusBreakMin" class="plusbtn">+</button>
<span id="breakMin" class="number">5</span>
<button id="minusBreakMin" class="minusbtn">-</button>
<br>
<div id="breakResetWrapper" class="resetWrapper">
<button id="breakReset" class="resetBtn">Reset</button>
</div>
</div>
</div>
</div>
<div class="pomodoroContainer">
<div class="pomodoro">
<div id="pomodoroTime">
00 : 00
</div>
</div>
</div>
<div class='playStop'>
<i class="fa fa-play btn" id="playPomodoro" aria-hidden="true"></i>
<i class="fa fa-stop btn" id="stopPomodoro" aria-hidden="true"></i>
</div>
</div>
</body>

Categories