How to convert a stopwatch to a count down timer in JS - javascript

Is it possible to modify that code of a stopwatch bellow in a way that it works as a count down timer that starts from 00:13:00 and stops at 00:00:00. The start and reset button should function as before.
//Define vars to hold time values
let seconds = 0;
let minutes = 0;
let hours = 0;
//Define vars to hold "display" value
let displaySeconds = 0;
let displayMinutes = 0;
let displayHours = 0;
//Define var to hold setInterval() function
let interval = null;
//Define var to hold stopwatch status
let status = "stopped";
//Stopwatch function (logic to determine when to increment next value, etc.)
function stopWatch(){
seconds++;
//Logic to determine when to increment next value
if(seconds / 60 === 1){
seconds = 0;
minutes++;
if(minutes / 60 === 1){
minutes = 0;
hours++;
}
}
//If seconds/minutes/hours are only one digit, add a leading 0 to the value
if(seconds < 10){
displaySeconds = "0" + seconds.toString();
}
else{
displaySeconds = seconds;
}
if(minutes < 10){
displayMinutes = "0" + minutes.toString();
}
else{
displayMinutes = minutes;
}
if(hours < 10){
displayHours = "0" + hours.toString();
}
else{
displayHours = hours;
}
//Display updated time values to user
document.getElementById("display").innerHTML = displayHours + ":" + displayMinutes + ":" + displaySeconds;
}
function startStop(){
if(status === "stopped"){
//Start the stopwatch (by calling the setInterval() function)
interval = window.setInterval(stopWatch, 1000);
document.getElementById("startStop").innerHTML = "Stop";
status = "started";
}
else{
window.clearInterval(interval);
document.getElementById("startStop").innerHTML = "Start";
status = "stopped";
}
}
//Function to reset the stopwatch
function reset(){
window.clearInterval(interval);
seconds = 0;
minutes = 0;
hours = 0;
document.getElementById("display").innerHTML = "00:00:00";
document.getElementById("startStop").innerHTML = "Start";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Stopwatch</title>
<link href="https://fonts.googleapis.com/css2?family=Concert+One&display=swap" rel="stylesheet">
<link rel="stylesheet" href="styles.css">
<script type="text/javascript" src="scripts.js"></script>
</head>
<body>
<div class="container">
<div id="display">
00:13:00
</div>
<div class="buttons">
<button id="startStop" onclick="startStop()">Start</button> <button id="reset" onclick="reset()">Reset</button>
</div>
</div>
</body>
</html>
I have tried setting the initial time 00:13:00 and using a -- operator instead of ++ operators. But it just shows negative time.
(Not including the CSS as it will stay the same)

The if statements below //Logic to determine when to increment next value need to be changed to seconds < 0 and minutes < 0
//Define vars to hold time values
let seconds = 0;
let minutes = 1;
let hours = 0;
//Define vars to hold "display" value
let displaySeconds = 0;
let displayMinutes = 0;
let displayHours = 0;
//Define var to hold setInterval() function
let interval = null;
//Define var to hold stopwatch status
let status = "stopped";
//Stopwatch function (logic to determine when to increment next value, etc.)
function stopWatch() {
seconds--;
//Logic to determine when to increment next value
if (seconds < 0) {
if (minutes === 0 && hours === 0) {
clearInterval(interval);
alert("done!");
return;
} else {
seconds = 59;
minutes--;
if (minutes < 0) {
minutes = 59;
hours--;
}
}
}
//If seconds/minutes/hours are only one digit, add a leading 0 to the value
if (seconds < 10) {
displaySeconds = "0" + seconds.toString();
} else {
displaySeconds = seconds;
}
if (minutes < 10) {
displayMinutes = "0" + minutes.toString();
} else {
displayMinutes = minutes;
}
if (hours < 10) {
displayHours = "0" + hours.toString();
} else {
displayHours = hours;
}
//Display updated time values to user
document.getElementById("display").innerHTML = displayHours + ":" + displayMinutes + ":" + displaySeconds;
}
function startStop() {
if (status === "stopped") {
//Start the stopwatch (by calling the setInterval() function)
interval = window.setInterval(stopWatch, 1000);
document.getElementById("startStop").innerHTML = "Stop";
status = "started";
} else {
window.clearInterval(interval);
document.getElementById("startStop").innerHTML = "Start";
status = "stopped";
}
}
//Function to reset the stopwatch
function reset() {
window.clearInterval(interval);
seconds = 0;
minutes = 13;
hours = 0;
document.getElementById("display").innerHTML = "00:00:00";
document.getElementById("startStop").innerHTML = "Start";
}
<div class="container">
<div id="display">
00:01:00
</div>
<div class="buttons">
<button id="startStop" onclick="startStop()">Start</button> <button id="reset" onclick="reset()">Reset</button>
</div>
</div>

Related

Why can't I switch between my "stop" and "start" buttons?

I'm making a stopwatch, and my codes is supposed to make the "start" button turn to "stop" button whenever I click on the "start" button and the opposite. My start button seems to work but when I try to switch it to "stop" it doesn't work. I don't know what is wrong, anybody can help me? Thank you so much!
This is my js:
let hours = 0
let seconds = 0
let minutes = 0
//define var to hold 'display' value
let displaySeconds = 0
let displayMinutes = 0
let displayHours = 0
//var to hold "setInterval" function
let interval = null
//Define var to hold stopwatch status
let status = "stopped"
//functions(logic to determine when to increment values,...)
function stopWatch() {
seconds++;
//logic to determine when to flip to next next value
if (seconds / 60 ===1){
seconds = 0;
minutes++;
if(minutes/ 60 ===1){
minutes = 0;
hours++;
}
}
//if second, minute, hrs are only one digits, add a leaing 0 to the value
if(seconds < 10){
displaySeconds = "0" + seconds.toString()
}else{
displaySeconds = seconds
}
if(minutes < 10){
displayMinutes = "0" + minutes.toString()
}else{
displayMinutess = minutes
}
if(hours < 10){
displayHours = "0" + hours.toString()
}else{
displayHours = hours
}
//display updated time values to user
document.getElementById('display').innerHTML = displayHours + ':' + displayMinutes + ":" + displaySeconds
}
function startStop(){
if(status === "stopped"){
//start the stopwatch by calling setInterval function
interval = window.setInterval(stopWatch, 1000)
document.getElementById('startStop').innerHTML = "stop"
status:"started"
}
else{
window.clearInterval(interval)//stop interval from running
document.getElementById('startStop').innerHTML = "start"
status = "stopped"
}
}
This is my html:
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<div id="display">
00:00:00
</div>
<div class="button">
<button id="startStop" onclick="startStop()">Start</button>
<button id="reset">Reset</button>
</div>
</div>
<script src="index.js"></script>
</body>
</html>
It is because you are using status: "started" instead of status = "started", you are writing the following statement inside the if block
if(status === "stopped"){
interval = window.setInterval(stopWatch, 1000)
document.getElementById('startStop').innerHTML = "stop"
status = "started"
}

Countdown It does not Work on a minute system

I have a simple code but there is a problem
How do I make this code work in a minute and a second system
Tried but only work a second!
You can look at the code
https://jsfiddle.net/o183pdqg/1/
I hope for help because I am really tired and I am looking for a solution
function secondPassed() {
var seconds = 120;
var countdownElement = document.getElementById('countdown');
var contentElement = document.getElementById('content');
var adsElement = document.getElementById('ads');
var minutes = Math.round((seconds - 30) / 60);
var remainingSeconds = seconds;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "";
} else {
seconds--;
}
adsElement.style.display = '';
countdownElement.innerHTML = remainingSeconds;
var interval = setInterval(function() {
countdownElement.innerHTML = --remainingSeconds;
if (remainingSeconds === 0) {
clearInterval(interval);
contentElement.style.display = '';
adsElement.style.display = 'none';
}
}, 1000);
}
<div id="container">
Send Code
<div id="ads" style="display: none">
<div id="countdown"></div>
<div>Sent!</div>
</div>
<div id="content" style="display: none">Error!</div>
</div>
you need to put variable minutes and seconds within setInterval function to make it work. Convert the time var remainingSeconds = seconds * 1000; from second to milisecond so it will make it easier when working with new Date().getTime().
To get minutes and second, try it using modulus (%) operator to get remaining time from your starting time.
var availability = true
function secondPassed() {
if (!availability) {
return false
}
var seconds = 120;
var countdownElement = document.getElementById('countdown');
var contentElement = document.getElementById('content');
var adsElement = document.getElementById('ads');
availability = false
adsElement.style.display = '';
contentElement.style.display = 'none';
function runInterval () {
var remainingSeconds = seconds * 1000;
let minutes = Math.floor(remainingSeconds % (1000*60*60)/ (1000*60));
let seconds1 = Math.floor(remainingSeconds % (1000*60) / 1000);
if (seconds1 < 10) {
seconds1 = "0" + seconds1;
}
document.getElementById('countdown').innerHTML = minutes + ":" + seconds1;
if (seconds == 0) {
// clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "";
} else {
seconds--;
}
if (remainingSeconds === 0) {
clearInterval(interval);
contentElement.style.display = '';
adsElement.style.display = 'none';
availability = true
}
}
var interval = setInterval(function() {
// countdownElement.innerHTML = --remainingSeconds;
runInterval ()
}, 1000);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div id="container">
Send Code
<div id="ads" style="display: none">
<div id="countdown"></div>
<div>Sent!</div>
</div>
<div id="content" style="display: none">Error!</div>
</div>
</body>
</html>
You can try with this answer
secondPassed = () => {
let remainingSeconds = 120;
const countdownElement = document.getElementById('countdown');
const contentElement = document.getElementById('content');
const adsElement = document.getElementById('ads');
adsElement.style.display = '';
const getPad = (num) => {
return (num < 10) ? '0' + num.toString() : num.toString();
}
const interval = setInterval(() => {
let minutes = Math.floor(remainingSeconds / 60) % 60;
let seconds = getPad(remainingSeconds % 60);
countdownElement.innerHTML = `${minutes} : ${seconds}`;
remainingSeconds--;
if (remainingSeconds == 0) {
clearInterval(interval);
contentElement.style.display = '';
adsElement.style.display = 'none';
}
}, 1000);
}

Stopwatch - keeping the elapsed time at zero before the start timer onclick handler is clicked

Stopwatch - keeping the elapsed time at zero before the start timer onclick handler is clicked
Hi, I have been working on a Javascript stopwatch for an interview test. I have an issue where the timer starts automatically when the browser loads. I have tried editing the add() function's 'if' statement but not having any joy with it. Can anyone help me?
var h1 = document.getElementsByTagName('h1')[0],
start = document.getElementById('start'),
stop = document.getElementById('stop'),
clear = document.getElementById('clear'),
milli = 0, seconds = 0, minutes = 0, hours = 0,
t;
function add() {
milli += 10;
if (milli >= 1000) {
milli = 0;
seconds++;
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) + "." + (milli > 90 ? milli : "0" + milli);
timer();
}
function timer() {
t = setTimeout(add, 10);
}
timer();
/* Start button */
start.onclick = timer;
/* Stop button */
stop.onclick = function() {
clearTimeout(t);
}
/* Clear button */
clear.onclick = function() {
h1.textContent = "00:00:00:00";
milli = 0; seconds = 0; minutes = 0; hours = 0;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Test Stopwatch</title>
<link rel="stylesheet" href="assets/css/styles.css">
</head>
<body>
<section>
<h1>
<time>00:00:000:00</time>
</h1>
<button id="start">START</button>
<button id="stop">STOP</button>
<button id="clear">CLEAR</button>
</section>
<script src="assets/js/script.js"></script>
</body>
</html>
You have a timer() call on the root of the javascript file scope so it is invoked automatically.
function timer() {
t = setTimeout(add, 10);
}
timer(); // This starts it automatically. remove it.
correct:
function timer() {
t = setTimeout(add, 10);
}

how to set the same id for multiple element in html

I want to use countdown timer for 10 element that creating at run time. each element has expire time so I want to show user how much time of of the expiration is remained.so I use a jquery file to do this .so I must use an id for a tag to show the remained time .when I use it for one element it works fine but when I use it for multiple element it just works for first element.how can I solve this problem to show the remained time for all elements
Jquery file
//var count = 1000;
//var counter = setInterval(timer, 1000);
//function timer() {
// count -= 1;
// if (count==1000) {
// clearInterval(counter);
// }
// document.getElementById("num").innerHTML = count;
//}
function CountDown() {
this.start_time = "02:00:00:23";
this.target_id = "#timer";
this.name = "timer";
}
CountDown.prototype.init=function(){
this.reset();
setInterval(this.name+'.tick()',1000);
}
CountDown.prototype.reset=function(){
time = this.start_time.split(":");
this.days = parseInt(time[0]);
this.hours = parseInt(time[1]);
this.minutes=parseInt(time[2]);
this.seconds = parseInt(time[3]);
this.update_target();
}
CountDown.prototype.tick=function(){
if (this.seconds > 0 || this.minutes > 0 || this.hours > 0 ||this.days>0) {
if (this.hours == 0 && this.minutes == 0 && this.seconds == 0) {
this.days = this.days - 1;
this.hours = 23;
this.minutes = 59;
this.seconds = 59;
}
if (this.minutes == 0 && this.seconds==0) {
this.hours = this.hours - 1;
this.minutes = 59;
this.seconds = 59;
}
else if (this.seconds == 0) {
this.minutes = this.minutes - 1;
this.seconds = 59;
}
else {
this.seconds = this.seconds - 1;
}
}
this.update_target();
}
CountDown.prototype.update_target = function () {
seconds = this.seconds;
minutes = this.minutes;
hours = this.hours;
days = this.days;
if (seconds<10)
seconds = "0"+seconds;
if (minutes < 10)
minutes = "0"+ minutes;
if (hours < 10)
hours = "0" + hours;
if (days < 10)
days = "0" + days;
$(this.target_id).val(days+":"+hours+":"+minutes + ":" + seconds)
// $(this.target_id).val(this.minutes+":"+seconds)
}
Html
<script src="~/Scripts/jquery-1.4.4.min.js"></script>
<script src="~/Scripts/countdown.js"></script>
<input type="text" id="timer" value=" " />
<script>
timer = new CountDown();
timer.init();
</script>
Id is unique in html use class instead .. more element can have the same class
$('.yourClass')
instead of
$('#yourId')
.
<script src="~/Scripts/jquery-1.4.4.min.js"></script>
<script src="~/Scripts/countdown.js"></script>
<input type="text" class="timer" value=" " />
<script>
timer = new CountDown();
timer.init();
</script>
function CountDown() {
this.start_time = "02:00:00:23";
this.target_id = ".timer";
this.name = "timer";
}
EDIT :
I've created a JSFiddle for it, can you precise your request ?
See it here
I changed this :
timer = new CountDown("02:00:00:23");
timer.init();
And this function :
function CountDown(start_time) {
this.start_time = start_time;
this.target_id = ".timer";
this.name = "timer";
}
Id's are unique and should only be used once in an html page. Also, and element should only have a single ID. Classes are not unique so multiple elements can have the same class, also, a single element can have multiple classes. Example:
<div class="exampleClass anotherClass"></div>
<div class="exampleClass></div>
<div class="exampleClass></div>
Instead of id="timer" use class="timer" then in your javascript file use $(".timer") to target those classes. So in your case instead of this.target_id = "#timer" use this.target_id =".timer";
Here's a good reference for classes and ids.

Timer to be displayed on a webpage

I want to add a count up timer to my webpage, as in, a label that contains 0:00:00 should start displaying 0:00:01 and so on until the stop button is clicked.
Is there a simple javascript/jquery solution to this?
<html>
<head>
<title>Home</title>
<script src="jquery-1.11.1.js">
</script>
<script>
$(document).ready(function(){
$("p").click(function(){
//psst. psst.
});
});
</script>
</head>
<body>
<form>
<table>
<tr>
<td><input type="text" id="project" placeholder="project"></td>
<td><p id="timer">0:00:00<p></td>
</tr>
</table>
</form>
</body>
</html>
I tried something in Vanilla JS HERE
var seconds=0, minutes=0, hours=0;
var counter;
var stop,start;
var counting = false;
window.onload = function () {
counter = document.getElementById('counter');
stop = document.getElementById('stop');
stop.onclick = function () {
counting = false;
}
start = document.getElementById('start');
start.onclick = function() {
counting = true;
timer();
}
counting = true;
timer();
}
function timer() {
if (seconds >= 60) {
minutes++;
seconds = 0;
}
if (minutes >= 60) {
hours++;
minutes = 0;
}
counter.innerHTML = hours + ":" + minutes + ":" + seconds;
if (counting) {
seconds++;
setTimeout(timer, 1000);
}
}
If you need more info leave a comment..
time.js
function time(id)
{
date = new Date;
h = date.getHours();
if(h<10)
{
h = "0"+h;
}
m = date.getMinutes();
if(m<10)
{
m = "0"+m;
}
s = date.getSeconds();
if(s<10)
{
s = "0"+s;
}
result = h+':'+m+':'+s;
document.getElementById(id).innerHTML = result;
// "setTimeout" call function "time" every 1 second (1000 milliseconds)
setTimeout('time("'+id+'");','1000');
return true;
}
HTML
<html>
<head>
<title>Time in Javascript</title>
<script type="text/javascript" src="time.js"></script>
</head>
<body>
<span id="time"></span>
<script type="text/javascript">window.onload = time('time');</script>
</body>
</html>
Try this way
Use https://github.com/jchavannes/jquery-timer
Include this files in head
<script src="http://code.jquery.com/jquery-1.8.3.js" type="text/javascript">
<script src="http://jchavannes.com/include/scripts/3p/jquery.timer.js" type="text/javascript">
Script
var Example1 = new (function() {
var $stopwatch, // Stopwatch element on the page
incrementTime = 70, // Timer speed in milliseconds
currentTime = 0, // Current time in hundredths of a second
updateTimer = function() {
$stopwatch.html(formatTime(currentTime));
currentTime += incrementTime / 10;
},
init = function() {
$stopwatch = $('#stopwatch');
Example1.Timer = $.timer(updateTimer, incrementTime, true);
};
this.resetStopwatch = function() {
currentTime = 0;
this.Timer.stop().once();
};
$(init);
});
function formatTime(time) {
var min = parseInt(time / 6000),
sec = parseInt(time / 100) - (min * 60),
hundredths = pad(time - (sec * 100) - (min * 6000), 2);
return (min > 0 ? pad(min, 2) : "00") + ":" + pad(sec, 2) + ":" + hundredths;
}
function pad(number, length) {
var str = '' + number;
while (str.length < length) {str = '0' + str;}
return str;
}
Example1();
DEMO
By using setInterval and Date
You can use button to stop and start timer.
var d = new Date();
d.setHours(0,0,0,0);
setInterval((function(){
return function(){
d.setSeconds(d.getSeconds()+1);
var t = d.toLocaleTimeString("en-US", {hour12: false});
document.getElementById("demo").innerHTML = t;
}
})(), 1000);
Fiddle Demo
Please try this fiddle for your solution.
JS.
var hour = 0;
var min = 0;
var second = 0;
var i=setInterval(function(){
second++;
if(second > 59){
second = 0;
min++;
if(min>59){
hour++;
min = 0;
}
}
var timer_time = (hour > 9 ? hour : '0'+hour)+':'+(min > 9 ? min : '0'+min)+':'+(second > 9 ? second : '0'+second);
$('#timer').html(timer_time);
}, 1000);
$('#stop_timer').click(function(){
clearInterval(i);
});
HTML
<p id='timer'>00:00:00</p>
<button id='stop_timer'>Stop Timer</button>
Thanks
Use timing events like documented at http://www.w3schools.com/js/js_timing.asp.

Categories

Resources