I have a timer with the progress bar. the timer works fine. but I want to move the progress bar with the timer. I'm using the bootstrap progress bar. if I remove the bar variable from the function the timer works fine but with the progress, it stops working. any suggestions? thank you :)
function startTimer(duration, display, bar) {
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;
bar.css('width', minutes + '%');
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
window.onload = function () {
var minutes = 60 * 15,
display = document.querySelector('#time');
bar = document.querySelector('#progressBar');
startTimer(minutes, display, bar);
};
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<div class="progress mx-auto mb-2" style="max-width: 300px;">
<div class="progress-bar bg-success" role="progressbar" id="progressBar" style="width: 100%" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<span id="time">15:00</span>
Use bar.style.width, .css() is a jQuery function.
For correct percentage, calculate total and remaining seconds and set bar width based on that
function startTimer(duration, display, bar) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
var totalSeconds = 15 * 60
, remainingSeconds = minutes * 60 + seconds
bar.style.width = (remainingSeconds*100/totalSeconds) + "%";
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 minutes = 60 * 15,
display = document.querySelector('#time');
bar = document.querySelector('#progressBar');
startTimer(minutes, display, bar);
};
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<div class="progress mx-auto mb-2" style="max-width: 300px;">
<div class="progress-bar bg-success" role="progressbar" id="progressBar" style="width: 100%" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<span id="time">15:00</span>
Related
I am trying to enable the user to set the value of a timer and then to see the countdown timer displayed on the webpage.
Here is my HTML code:
<p>Timer:</p>
<input type="text" name="timing" id="demoC" style="height:50px;" value="3">
<div id="answer">Your dish will be ready in <span id="time"></span> minutes!</div>
<input type="submit" name="submit" class="submit" value="Submit">
And here is my JS code:
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.text(minutes + ":" + seconds);
if (--timer < 0) {
timer = 0;
var html = "Your dish is ready!!";
document.getElementById('answer').innerHTML = html;
}
}, 1000);
}
jQuery(function ($) {
var myVar = 60 * document.getElementById('demoC').value,
display = $('#time');
startTimer(myVar, display);
});
This code is working because in the HTML file, I hardcoded the value to 3 minutes directly.
But I would like to remove this value="3"and be able to set it up manually in the input field.
But when I am doing that, the timer is not displayed.
First, you should add the 'id'-attribute to the input element:
<input type="submit" name="submit" class="submit" value="Submit" id="submit">
But just setting the function glitches out the timer if the user inputs multiple values, so you should change your code like this:
var clearIntervalId;
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
clearIntervalId = 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.text(minutes + ":" + seconds);
if (--timer < 0) {
timer = 0;
var html = "Your dish is ready!!";
document.getElementById('answer').innerHTML = html;
}
}, 1000);
}
$("#submit").click(function(){
var myVar = 60 * document.getElementById('demoC').value,
display = $('#time');
if (typeof clearIntervalId !== 'undefined') {
clearInterval(clearIntervalId)
}
startTimer(myVar, display);
});
clearIntervalId is used, so that the previous running setInterval()-function is getting cleared out everytime the user clicks the button, so that there won't be interfering changes in the current minutes + seconds.
What do you need is a trigger for the startTimer function after event
and in your code the event is a button click
Add id attribute to your button
<input type="submit" id="submit" name="submit" class="submit" value="Submit">
and add click event listener to your button
$("#submit").on("click",function(){
var myVar = 60 * document.getElementById('demoC').value,
display = $('#time');
startTimer(myVar, display);
})
jQuery(function ($) {
$("#submit").on("click",function(){
var myVar = 60 * document.getElementById('demoC').value,
display = $('#time');
startTimer(myVar, display);
})
});
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.text(minutes + ":" + seconds);
if (--timer < 0) {
timer = 0;
var html = "Your dish is ready!!";
document.getElementById('answer').innerHTML = html;
}
}, 1000);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Timer:</p>
<input type="text" name="timing" id="demoC" style="height:50px;" value="3">
<div id="answer">Your dish will be ready in <span id="time"></span> minutes!</div>
<input type="submit" id="submit" name="submit" class="submit" value="Submit">
I have a page with timers. the code for my latest timer only functions properly. but the rest of the timers don't such as the 10 minute timer. It only shows you the set time for the timer. Is my latest code overriding my other code? Are variables being mixed between the two timers? I'm planning on adding several timers to the page, but I got stuck when this happened.
Link to code: http://jsfiddle.net/vtoLx02j/2/
<body>
<div id="1Div">
<h4>Question goes here?</h4>
<input type="text"id="name1"/>
<button onclick="myFunction1()" id="button0" class="button3">Enter</button>
</div>
<div id="2Div" style="display:none;">
<h4 id=typeE>How much time do you think you need in minutes?</h4>
<button onclick="myFunction2()" id="button1" class="button3">10 minutes</button>
<button onclick="myFunction3()" id="button2" class="button3">20 minutes</button>
</div>
<script>
function myFunction1(){
document.getElementById("1Div").style.display="none";
document.getElementById("2Div").style.display="block";
}
</script>
<script>
function myFunction2(){
document.getElementById("2Div").style.display="none";
document.getElementById("timer10").style.display="block";
}
</script>
<script>
function myFunction3(){
document.getElementById("2Div").style.display="none";
document.getElementById("timer20").style.display="block";
}
</script>
<div id="timer10" style="display:none">
<script>
function startTimer10(duration10, display10) {
var timer10 = duration10, minutes10, seconds10;
setInterval(function () {
minutes10 = parseInt(timer10 / 60, 10);
seconds10 = parseInt(timer10 % 60, 10);
minutes10 = minutes10 < 10 ? "0" + minutes10 : minutes10;
seconds10 = seconds10 < 10 ? "0" + seconds10 : seconds10;
display10.textContent = minutes10 + ":" + seconds10;
if (--timer10 < 0) {
timer10 = duration10;
}
}, 1000);
}
window.onload = function () {
var tenMinutes = 60 * 10,
display10 = document.querySelector('#time10');
startTimer10(tenMinutes, display10);
};
</script>
<body>
<center><div><span id="time10">10:00</span></div></center>
</body>
</div>
<div id="timer20" style="display:none">
<script>
function startTimer20(duration20, display20) {
var timer20 = duration20, minutes20, seconds20;
setInterval(function () {
minutes20 = parseInt(timer20 / 60, 10);
seconds20 = parseInt(timer20 % 60, 10);
minutes20 = minutes20 < 10 ? "0" + minutes20 : minutes20;
seconds20 = seconds20 < 10 ? "0" + seconds20 : seconds20;
display20.textContent = minutes20 + ":" + seconds20;
if (--timer20 < 0) {
timer20 = duration20;
}
}, 1000);
}
window.onload = function () {
var twentyMinutes = 60 * 20,
display20 = document.querySelector('#time20');
startTimer20(twentyMinutes, display20);
};
</script>
<body>
<center><div><span id="time20">20:00</span></div></center>
</body>
</div>
</body>
You can simply combine all your functions into single startTimer() function.
I am not sure why you are repeating your code again and again to achieve the same results. Its good to have less code but have the same results.
So here's is what i have done and simplified your code.
I have combined both timers into one function
You do not need to use display none and block again on show time duration
When you click on the timer just pass the minutes to the timer function and the span will start displaying the time remaining
You do no need two span to display timer separately you can do all that in one span
You were using script tag so many times which are unnecessary
Both timers are working perfectly with less code and same results.
You can have multiple timers now you just need to pass the minutes to your startTimer() function and timer will start from the given time.
Live Demo
//Start timer
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);
}
//1
function myFunction1() {
document.getElementById("1Div").style.display = "none";
document.getElementById("2Div").style.display = "block";
}
//10 Minutes
function myFunction2() {
document.getElementById("2Div").style.display = "none";
var tenMinutes = 60 * 10,
display10 = document.querySelector('#timerDuration');
startTimer(tenMinutes, display10);
}
//20 minutes
function myFunction3() {
document.getElementById("2Div").style.display = "none";
var twentyMinutes = 60 * 20,
display20 = document.querySelector('#timerDuration');
startTimer(twentyMinutes, display20);
}
<body>
<div id="1Div">
<h4>Question goes here?</h4>
<input type="text" id="name1" />
<button onclick="myFunction1()" id="button0" class="button3">Enter</button>
</div>
<div id="2Div" style="display:none;">
<h4 id=typeE>How much time do you think you need in minutes?</h4>
<button onclick="myFunction2()" id="button1" class="button3">10 minutes</button>
<button onclick="myFunction3()" id="button2" class="button3">20 minutes</button>
</div>
<center>
<div><span id="timerDuration"></span></div>
</center>
</body>
I have a simple Bootstrap page that includes a 45 second countdown timer and a button which I intend to include on a bigger project later. The countdown timer will start on a click of the button.
What I wanted to do is that when I click on the button again within the 45 seconds countdown interval, the counter will reset. I am not able to do that. What I tried to do is to use the clearInterval function at the very beginning of the errorTimer function. But, it did not work.
Here are my codes:
// Timer for error message - 45 seconds.
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);
}
function errorTimer() {
var fortyFiveSeconds = 60 * .75,
display = document.querySelector('#time');
startTimer(fortyFiveSeconds, display);
};
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.2.1/js/bootstrap.min.js"></script>
<div class="container-fluid">
<div class="row">
<div class="col-md-12 mt-5"> </div>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4 text-center">
<p id="time"></p>
</div>
<div class="col-md-4"></div>
</div>
</div>
<button type="button" class="btn btn-info" onclick="errorTimer()">Submit Button</button>
Use clearInterval like this
...
// Timer for error message - 45 seconds.
var timerId;
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
if(timerId != undefined) {
clearInterval(timerId)
}
timerId = 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 errorTimer () {
var fortyFiveSeconds = 60 * .75,
display = document.querySelector('#time');
startTimer(fortyFiveSeconds, display);
};
...
As #Shidersz mentioned, you need to store the id associated with the interval and use that id to clear the interval before resetting the clock.
// Timer for error message - 45 seconds.
var id = null;
function startTimer(duration, display) {
if (id !== null) {
clearInterval(id);
id = null;
}
var timer = duration,
minutes, seconds;
id = 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 errorTimer() {
var fortyFiveSeconds = 60 * .75,
display = document.querySelector('#time');
startTimer(fortyFiveSeconds, display);
};
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.2.1/js/bootstrap.min.js"></script>
<div class="container-fluid">
<div class="row">
<div class="col-md-12 mt-5"> </div>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4 text-center">
<p id="time"></p>
</div>
<div class="col-md-4"></div>
</div>
</div>
<button type="button" class="btn btn-info" onclick="errorTimer()">Submit Button</button>
You could stop the timer by clearing the interval:
// Timer for error message - 45 seconds.
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
var interval = 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);
return function(){ clearInterval(interval); };
}
function errorTimer () {
var fortyFiveSeconds = 60 * .75,
var display = document.querySelector('#time');
var stopper = startTimer(fortyFiveSeconds, display);
setTimeout(stopper, 20 * 1000); // stop timer 20 seconds later.
};
I make use of a simple function returned by the startTimer function, that can be used to clear the interval at a later point.
I have this code
var duration = 60 * $(".duration").val(),
display = $(".timer");
startTimer(duration, display);
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.html(minutes + ":" + seconds);
if (--timer < 0) {
display.html("DONE!");
}
}, 1000);
}
I have + button to let the user add multiple timers like this
<input type="text" class="duration" /> //Desired duration for first timer
<div class="timer"></div>
<input type="text" class="duration" /> //Desired duration for second timer
<div class="timer"></div>
<input type="text" class="duration" /> //Desired duration for third timer
<div class="timer"></div>
after that I want the user to click a button to start the timers but one at a time after the first timer finished the second one starts and etc
Thank you
Here's the first way that came to mind that didn't involve much change to your existing startTimer() function - basically I just added a callback argument, and then another function to start the next timer. (This code could be tidied up quite a bit, but it should give you some ideas...)
$("button").click(function() {
var durations = $(".duration");
var current = -1;
durations.prop("disabled", true);
$(this).prop("disabled", true);
function startNext() {
if (++current < durations.length)
startTimer(durations.eq(current).val() * 60,
durations.eq(current).next(),
startNext);
else {
durations.prop("disabled", false);
$("button").prop("disabled", false);
}
}
startNext();
function startTimer(duration, display, callback) {
var timer = duration,
minutes, seconds;
var intId = 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.html(minutes + ":" + seconds);
if (--timer < 0) {
display.html("DONE!");
clearInterval(intId);
callback();
}
}, 1000);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
First:
<input type="text" class="duration" value="0.05" />
<div class="timer"></div>
Second:
<input type="text" class="duration" value="0.05" />
<div class="timer"></div>
Third:
<input type="text" class="duration" value="0.1" />
<div class="timer"></div>
<button>Start</button>
I am implementing a stopwatch by using Javascript. I have basic html document setup and a javascript file called stopwatch.js in which I have the following code. I make use of setInterval function to execute the clockRunning function every 1 second(1000ms). This gives me control over sec, min and hour to increment them accordingly, but I am having difficulty with inserting millisecond into the stopwatch. How should I increment the millisecond from 0 to 1000 and then reset to zero?
I have tried by decreasing the interval time for setInterval function to be called every 1ms and then set millisecond variable to time%1000 in which time variable is increased by 1 every time the function is called. But it does not give the result I want. The millisecond seems to be increasing way too slow.
var running = 0
var time = 0;
var hour = 0;
var min = 0;
var sec = 0;
var millisec = 0;
function start(){
started = window.setInterval(clockRunning, 1000);
}
function stop(){
window.clearInterval(started);
}
function clockRunning(){
time++;
sec++;
if (sec == 60){
min += 1;
sec = 0;
if (min == 60){
hour += 1;
min = 0;
}
}
document.getElementById("display-area").innerHTML = (hour ? (hour > 9 ? hour : "0" + hour) : "00")
+ ":" + (min ? (min > 9 ? min : "0" + min) : "00") + ":" + (sec > 9 ? sec : "0"
+ sec);
};
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Stopwatch</title>
<script src="stopwatch.js"></script>
<style>
#display-area { font-size: 20pt; }
</style>
</head>
<body>
<div>
<output id="display-area">00:00:00.000</output>
</div>
<div>
<button id="toggle-button" onClick="start()">Start</button>
<button id="toggle-button" onClick="stop()">Stop</button>
<button id="reset-button">Reset</button>
</div>
</body>
</html>
You should keep track of the starting time then subtract that time from the current time using a Date:
var timeBegan = null
, timeStopped = null
, stoppedDuration = 0
, started = null;
function start() {
if (timeBegan === null) {
timeBegan = new Date();
}
if (timeStopped !== null) {
stoppedDuration += (new Date() - timeStopped);
}
console.log(stoppedDuration);
started = setInterval(clockRunning, 10);
}
function stop() {
timeStopped = new Date();
clearInterval(started);
}
function reset() {
clearInterval(started);
stoppedDuration = 0;
timeBegan = null;
timeStopped = null;
document.getElementById("display-area").innerHTML = "00:00:00.000";
}
function clockRunning(){
var currentTime = new Date()
, timeElapsed = new Date(currentTime - timeBegan - stoppedDuration)
, hour = timeElapsed.getUTCHours()
, min = timeElapsed.getUTCMinutes()
, sec = timeElapsed.getUTCSeconds()
, ms = timeElapsed.getUTCMilliseconds();
document.getElementById("display-area").innerHTML =
(hour > 9 ? hour : "0" + hour) + ":" +
(min > 9 ? min : "0" + min) + ":" +
(sec > 9 ? sec : "0" + sec) + "." +
(ms > 99 ? ms : ms > 9 ? "0" + ms : "00" + ms);
};
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Stopwatch</title>
<style>
#display-area { font-size: 20pt; }
</style>
</head>
<body>
<div>
<output id="display-area">00:00:00.000</output>
</div>
<div>
<button id="toggle-button" onClick="start()">Start</button>
<button id="toggle-button" onClick="stop()">Stop</button>
<button id="reset-button" onClick="reset()">Reset</button>
</div>
</body>
</html>
The reason you were seeing the milliseconds "lagging" before was that setInterval is notorious for not firing exactly when you specify. You can get around this using the strategy above.
Update: You could keep track of how long the timer has "paused" between resets. Updated my answer to accommodate this.
complete code here
$(document).ready(function () {
var milliseconds;
var hours;
var minutes;
var seconds;
var interval;
var count = 0;
var lap;
var i = 0;
$(".heading").slideDown("slow"); //slide down heading countdown.
// click function to start timer
$(".start").click(function () {
$(".start").hide();
$(".pause").show(100); // show pause button
$("#end").text("Stopwatch Started"); // change text.
interval = setInterval(newtimer, 10); // run the countdown interval of 1000 millisecond
});
function newtimer() {
hours = parseInt(count * 10 / 1000 / 60 / 60);// calculate hours
minutes = parseInt(count * 10 / 1000 / 60); // calculate minutes
seconds = parseInt((count * 10 / 1000)%60);// calculate seconds
milliseconds = parseInt((count*10) % 1000); // calculate milliseconds
/* display digits in clock manner */
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
count++; // increment in count.
$(".seconds").text(hours + " : " + minutes + " : " + seconds + " : " + milliseconds);
}
/* click function to pause timer*/
$(".pause").click(function () {
$(".start").hide(); //hide start button
$(".restart").hide(); //hide restart button
$(".pause").hide();
$(".resume").show(); // show resume button.
$("#end").text("Stopwatch Paused");
clearInterval(interval); //clear interval will stop the count.
i = i + 1;
lap = " " + hours + " : " + minutes + " : " + seconds + " : " + milliseconds;
$(".lap").append('<p>' + 'Time Lap' + "-" + i + lap + '</p>'); // add p tag in div and count no. of laps.
});
/* click function to resume the countdown */
$(".resume").click(function () {
$("#end").text("Stopwatch Resumed");// change end text.
$(".pause").show();
$(".resume").hide();
interval = setInterval(newtimer, 10);// interval to function new timer. count will remain same where paused.
});
/* click function to stop stopwatch */
$(".stop").click(function () {
$("#end").text("Stopwatch Stopped");
$(".restart").show(); //show restart button
$(".resume").hide(); // hide resume button
$(".start").hide();// hide start button
$(".pause").hide();
$(".lap p").remove(); // remove laps.
clearInterval(interval);
});
/*click function to restart stopwatch*/
$(".restart").click(function () {
$("#end").text("Stopwatch Restarted");// change end text.
$(".restart").hide();
$(".pause").show();
count = 0; // count reset to zero
interval = setInterval(newtimer, 10); //time interval to function new timer
});
/* click function on class reset to reset the countdown */
$(".reset").click(function () {
$(".seconds").text("00 : 00 : 00 : 00"); // set display to initial value.
$(".resume").hide(); // hide resume button
$(".start").show(); // show start button
$(".pause").hide(); // hide pause button
$(".restart").hide(); // hide restart button
$("#end").text(" "); // change end text
$(".lap p").remove(); // remove p tag from div
clearInterval(interval); // clear interval
count = 0; // reset count to initial value.
});
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>stopwatch</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script></head>
<body style="font-family: cursive;">
<div class="container-fluid clearfix" style="padding:100px; background-color:lightgrey;">
<div style="width:25%; float:left"><img src="./bn.jpg" alt="stopwatch" style="width:100%"></div>
<div class="heading" style="color:#165caa;display:none;margin-left: 365px;font-size: 84px">STOPWATCH</div>
<div class="seconds" style="font-size: 46px;text-align:center;margin-top:30px "> 00 : 00 : 00 : 00</div>
<div style="text-align:center;">
<button class="start mt-3 px-4 btn btn-success">START</button>
<button class="restart mt-3 px-4 btn btn-success" style="display:none">RESTART</button>
<button class="resume mt-3 px-4 btn btn-success" style="display:none">RESUME</button>
<button class="pause mt-3 px-4 btn btn-warning" style="display: none">PAUSE</button>
<button class="stop mt-3 px-4 btn btn-dark">STOP</button>
<button class="reset mt-3 px-4 btn btn-danger">RESET</button>
</div>
<p id="end" style="font-size:32px ;margin-top:30px;text-align:center"></p>
<div class="lap" style="text-align: center; font-size:16px;font-family: monospace;"></div>
</div>
</body>
</html>
BUG FIX!!!
I noticed the Start, Stop, Reset would not work if you hit Start more than once with the code above. I was able to fix this by tweaking the start function!
function start() {
if (timeBegan === null) {
timeBegan = new Date();
}else {
clearInterval(started);
};
if (timeStopped !== null) {
stoppedDuration += (new Date() - timeStopped);
};
if (stoppedDuration < 1000){
console.log(stoppedDuration+' ms');
};
if (stoppedDuration > 1000){
console.log(stoppedDuration/1000+' seconds');
};
started = setInterval(clockRunning, 10);
return stoppedDuration }