Stopwatch I made using JS not working - javascript

I've run the code multiple times trying to fix any error I have found in the code but it just doesn't seem to work.
I'm using the setInterval() loop. The function does not even run once. What could the problem be?
function stopWatch () {
var hours = Number(document.getElementById('hours').innerHTML);
var minutes = Number(document.getElementById('minutes').innerHTML);
var seconds = Number(document.getElementById('seconds').innerHTML);
if (seconds<60) {
seconds++
} else {
seconds = 0;
minutes++
}
if (minutes == 60) {
minutes = 0;
hours++
}
if (seconds.length==2) {
document.getElementById('seconds').innerHTML = seconds;
} else {
document.getElementById('seconds').innerHTML = '0' + seconds;
}
if (minutes.length==2) {
document.getElementById('minutes').innerHTML = minutes;
} else {
document.getElementById('minutes').innerHTML = '0' + minutes;
}
if (hours.length==2) {
document.getElementById('hours').innerHTML = hours;
}
if (hours.length==1) {
document.getElementById('hours').innerHTML = '0' + hours;
}
}
setInterval(stopWatch,1000)
<html>
<head></head>
<body>
<p>
<span id='hours'>00</span>:<span id='minutes'>00</span>:<span id='seconds'>00</span>
</p>
</body>
</html>

Your code only runs once. You need to use a loop of some description.
There are many ways to do this. A simple example would be to use setInterval to call the inners of your function every second.
You also have an error in your logic. You shouldn't be checking the length of the number (seconds.length==2). You should check wether the number is greater than 9 (seconds > 9):
function stopWatch() {
setInterval(function() {
var hours = Number(document.getElementById('hours').innerHTML);
var minutes = Number(document.getElementById('minutes').innerHTML);
var seconds = Number(document.getElementById('seconds').innerHTML);
if (seconds < 60) {
seconds++
} else {
seconds = 0;
minutes++
}
if (minutes == 60) {
minutes = 0;
hours++
}
if (seconds > 9) {
document.getElementById('seconds').innerHTML = seconds;
} else {
document.getElementById('seconds').innerHTML = '0' + seconds;
}
if (minutes > 9) {
document.getElementById('minutes').innerHTML = minutes;
} else {
document.getElementById('minutes').innerHTML = '0' + minutes;
}
if (hours > 9) {
document.getElementById('hours').innerHTML = hours;
} else {
document.getElementById('hours').innerHTML = '0' + hours;
}
}, 1000);
}
stopWatch()
<html>
<head></head>
<body>
<p>
<span id='hours'>00</span>:<span id='minutes'>00</span>:<span id='seconds'>00</span>
</p>
</body>
</html>

You mean why the stopwatch is not running?
You should wrap it in a setInteraval for it to update every second:
setInterval(function() {
stopWatch()
},1000);

Related

prevent timer to reset after page refresh site

I have count-up timer and it reset every time after refreshing page or closing tab how can I can continue timer after refreshing or closing page so that after that i can insert that time in database.
I want to also set setInterval for after serval time to update time and store that time .
here is html code :
var h1 = document.getElementById("displaytime"),
start = document.getElementById("start"),
reset = document.getElementById("reset"),
pause = document.getElementById("pause"),
reset_timer = document.getElementById("displaytime"),
seconds = 0,
minutes = 0,
hours = 0,
count = 0,
t = -1;
function timer() {
t = setTimeout(add, 1000);
}
function add() {
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);
timer();
}
function display_timer() {
count++;
console.log(displaytime);
}
setInterval(display_timer ,5000);
start.addEventListener("click", function() {
seconds = 0; minutes = 0; hours = 0;
clearInterval(t);
timer();
});
reset.addEventListener("click", function() {
clearTimeout(t);
reset_timer.innerHTML = '00:00:00';
pause.innerHTML = 'Pause';
});
pause.addEventListener('click', function(e) {
if (t == -1) {
pause.innerHTML = 'Pause';
timer();
} else {
pause.innerHTML = "Resume";
clearInterval(t);
t = -1;
}
});
<html>
<head>
<title>Timer</title>
</head>
<body>
<div class="Timer">
<section id="stopWatch">
<h1 id="displaytime">00:00:00</h1>
<button id="start">Start</button>
<button id="pause">Pause</button>
<button id="reset" >Reset</button>
</section>
</div>
</body>
</html>

JS interval not incrementing timer

The button I am listening in on and span element I want to
increment my timer in.
<p class="text2">art</p><br />
<p class="clocktext">
<span id="artSession">
<?php displayTime("art"); ?>
</span>
</p><br />
<button id="artBtn"> record </button><br />
<script type="text/javascript" src="includes/jquery.js"></script>
<script type="text/javascript" src="includes/jsfunctions.js"></script>
Here is my js functions file im calling from
// Beginning of tracker functionality
// variables to begin with
var interval;
var hours = 0;
var minutes = 0;
var seconds = 0;
var displayHrs = 0;
var displayMins = 0;
var displaySecs = 0;
var end, start, totalTime;
var timerStatus = false;
function sessionTimer() {
seconds = seconds + 1;
if(seconds >= 60 ) {
minutes++;
seconds = 0;
} else if ( minutes >= 60 ) {
hours++;
minutes = 0;
}
// logic to add leading 0
if( seconds < 10 ) {
displaySecs = '0' + seconds;
} else {
displaySecs = seconds;
} if( minutes < 10 ) {
displayMins = '0' + minutes;
} else {
displayMins = minutes;
} if( hours < 10 ) {
displayHrs = '0' + hours;
} else {
displayHrs = hours;
}
recordTime = displayHrs + ':' + displayMins + ':' + displaySecs;
document.getElementById('artSession').innerHTML = recordTime;
} // end of custom timer function
function buttonListening(catBtnId, catBtn, catSession, catSessionId, catagory) {
$(catBtnId).click(function() {
if(timerStatus == false) {
interval = setInterval(sessionTimer(), 1000);
document.getElementById(catBtn).innerHTML = 'stop';
timerStatus = true;
start = new Date();
}
else if (timerStatus == true) {
clearInterval(interval);
document.getElementById(catBtn).innerHTML = 'record';
end = new Date();
totalTime = end.getTime() - start.getTime();
timerStatus = false;
// reset timer values
hours = 0;
minutes = 0;
seconds = 0;
displayHrs = 0;
displayMins = 0;
displaySecs = 0;
// logic to add leading 0
if( seconds < 10 ) {
displaySecs = '0' + seconds;
} else {
displaySecs = seconds;
} if( minutes < 10 ){
displayMins = '0' + minutes;
} else {
displayMins = minutes;
} if( hours < 10 ){
displayHrs = '0' + hours;
} else {
displayHrs = hours;
}
//display formatted time in div
recordTime = displayHrs + ':' + displayMins + ':' + displaySecs;
document.getElementById(catSession).innerHTML = recordTime;
//#sign required !!include full path
$(catSessionId).load( 'includes/submit_time.php', {
postTimeCat: catagory ,
postTotalTime: totalTime
});
}
});
} // end of custom function storing btn event ---------------------------------------
buttonListening("#artBtn","artBtn","artSession","#artSession","art");
}); // end of js
Not quite sure where I'm going wrong. It was all working earlier today... GAHHH this project forsure has empowered me to start using github. Hope one of you guys can help me :C spent like all day smashing face off keyboard to get this thing to work. pet project almost done!
timeInterval = setInterval(sessionTimer(), 1000);
don't need parentheses '()' when passing function name in setInterval()
timeInterval = setInterval(sessionTimer, 1000);
hope this saves someone 4hrs

My stopwatch is acting funny - Javascript

I've been going about this for a while. Whenever I click "start" more than once, it adds up. If you notice, if I click "start" twice, the counting on my clock starts to act funny :
var h1 = document.getElementsByTagName('h1')[0],
start = document.getElementById('start'),
stop = document.getElementById('stop'),
clear = document.getElementById('clear'),
seconds = 0,
minutes = 0,
GG;
function add() {
seconds++;
if (seconds >= 60) {
seconds = 0;
minutes++;
if (minutes >= 60) {
minutes = 0;
}
}
h1.textContent =
(minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") +
":" + (seconds > 9 ? seconds : "0" + seconds);
timer();
}
function timer() {
GG = setTimeout(add, 1000);
}
timer();
start.onclick = timer;
stop.onclick = function() {
clearTimeout(GG);
}
clear.onclick = function() {
h1.textContent = "00:00";
seconds = 0;
minutes = 0;
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="time-container">
<h1><time>00:00</time></h1>
<button id="start">start</button>
<button id="stop">stop</button>
<button id="clear">clear</button>
</div>
</body>
</html>
I have to press STOP , N times as many as START.
If I want to fix this, to make any succeeding presses to START will not matter. Only one counting execution will be running at any time.
Add a variable to check click on start
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="time-container">
<h1><time>00:00</time></h1>
<button id="start">start</button>
<button id="stop">stop</button>
<button id="clear">clear</button>
</div>
</body>
<script>
var h1 = document.getElementsByTagName('h1')[0]
, start = document.getElementById('start')
, stop = document.getElementById('stop')
, clear = document.getElementById('clear')
, seconds = 0
, minutes = 0
, GG
, flag = true;
function add() {
seconds++;
if (seconds >= 60) {
seconds = 0;
minutes++;
if (minutes >= 60) {
minutes = 0;
}
}
h1.textContent = (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);
timer();
}
function timer() {
GG = setTimeout(add, 1000);
}
start.onclick = function () {
if(flag)
{
timer();
flag = false;
}
}
stop.onclick = function () {
clearTimeout(GG);
flag = true;
}
clear.onclick = function () {
h1.textContent = "00:00";
seconds = 0;
minutes = 0;
}
</script>
</html>

How can i put this javascript into the scripts folder and still work? (C# MVC 5)

Below is my code in C# MVC 5. I have made a partial view called _ClockPartial.cshtml that is a simple stopwatch that i am putting into the main page Index.cshtml using "#Html.Partial("_ClockPartial")".
My question is how do i separate the javascript into the scripts folder (~/Scripts/clocker.js) but still have it function properly? When i tried to separate it myself, i haven't gotten it to properly work yet. I have heard you can't do this in partial views but i'm not sure why. Even if i can't do it in partial i would still like to know how to separate the javascript into its own file and call it in one of my .cshtml views. Thanks for your help in advance!
First file is my Index.cshtml
#{
ViewBag.Title = "Home Page";
}
#using Microsoft.AspNet.Identity
#Scripts.Render("~/bundles/jquery")
<div class="jumbotron">
<h1>Clocker</h1>
<p class="lead">Welcome to clocker! Please sign in to start clocking your hours! Don't do too little or your hard earned cash goes into the punishiment piggy bank!</p>
#if (Request.IsAuthenticated)
{
#Html.Partial("_ClockPartial")
}
<p>Learn more ยป</p>
</div>
And this is _ClockPartial.cshtml
#Scripts.Render("~/bundles/jquery")
<h2><time>03:00:00</time></h2>
<button id="start">start</button>
<button id="stop">stop</button>
<button id="clear">clear</button>
<script type="text/javascript">
$(document).ready(function () {
var h1 = document.getElementsByTagName('h2')[0],
start = document.getElementById('start'),
stop = document.getElementById('stop'),
clear = document.getElementById('clear'),
seconds = 0, minutes = 0, hours = 3,
isRunning = false,
t;
/* increments timer */
function add() {
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);
timer();
}
/* decrements timer */
function subtract() {
seconds--;
if (seconds < 0) {
seconds = 59;
minutes--;
if (minutes < 0) {
minutes = 59;
hours--;
}
}
h1.textContent = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);
timer();
}
function timer() {
t = setTimeout(subtract, 1000);
}
/* enable following line to start timer automatically */
//timer();
/* Start button */
start.onclick = function () {
if (!isRunning) {
timer();
isRunning = true;
}
}
/* Stop button */
stop.onclick = function () {
clearTimeout(t);
isRunning = false;
}
/* Clear button */
clear.onclick = function () {
h1.textContent = "03:00:00";
seconds = 0; minutes = 0; hours = 3;
isRunning = false;
}
});
</script>
<p></p>
Create a new js file in the Scripts folder and add the following code of your partial view in it, let's say it's name is clocker.js:
$(document).ready(function () {
var h1 = document.getElementsByTagName('h2')[0],
start = document.getElementById('start'),
stop = document.getElementById('stop'),
clear = document.getElementById('clear'),
seconds = 0, minutes = 0, hours = 3,
isRunning = false,
t;
/* increments timer */
function add() {
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);
timer();
}
/* decrements timer */
function subtract() {
seconds--;
if (seconds < 0) {
seconds = 59;
minutes--;
if (minutes < 0) {
minutes = 59;
hours--;
}
}
h1.textContent = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);
timer();
}
function timer() {
t = setTimeout(subtract, 1000);
}
/* enable following line to start timer automatically */
//timer();
/* Start button */
start.onclick = function () {
if (!isRunning) {
timer();
isRunning = true;
}
}
/* Stop button */
stop.onclick = function () {
clearTimeout(t);
isRunning = false;
}
/* Clear button */
clear.onclick = function () {
h1.textContent = "03:00:00";
seconds = 0; minutes = 0; hours = 3;
isRunning = false;
}
});
Now modify the BundleConfig.cs file which is normally location in App_Start folder in the project and include the new js file in the bundles collection in RegisterBundles method after all other bundles there like:
bundles.Add(new ScriptBundle("~/bundles/clocker").Include(
"~/Scripts/clocker.js"));
Now in your main view after other scripts include, add include for this script as well:
#{
ViewBag.Title = "Home Page";
}
#using Microsoft.AspNet.Identity
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/clocker")
and now your partial would look like:
<h2><time>03:00:00</time></h2>
<button id="start">start</button>
<button id="stop">stop</button>
<button id="clear">clear</button>
Hope it helps!

Javascript countdown timer with 05 instead of 5 seconds?

I have created this one in JavaScript! It is a timer counting down time from 14:59 to 00:00 minutes. What I need to do is prevent seconds from going into one digit.
For example:
14:05 - allowed and needed to achieve
14:5 - not allowed and I need to get rid of this situation.
<html>
<head>
<script type="text/javascript">
var interval;
var minutes = 14;
var seconds = 05;
window.onload = function () {
countdown('atskaite');
}
function countdown(element) {
interval = setInterval(function () {
var el = document.getElementById(element);
if (seconds == 0) {
if (minutes == 0) {
clearInterval(interval);
return;
} else {
minutes--;
seconds = 60;
}
}
el.innerHTML = minutes + ':' + seconds;
seconds--;
}, 1000);
}
</script>
</head>
<body>
<div id="atskaite"></div>
</body>
</html>
Any help, please?
Quick and easy:
minutes + ':' + ("0"+seconds).slice(-2);
Simply add a check before you assign el.innerHTML, like so:
if (seconds < 10) seconds = '0' + seconds;

Categories