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

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"
}

Related

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

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>

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);
}

Failed to start countdown for the second time during operation

I am using the following code and giving a second click to the same start countdown button not clean the first process, so there are two counts at the same time. How do I stop the first process when the second start?
Thank you very much in advance.
function countdown(element, minutes, seconds) {
// Fetch the display element
var el = document.getElementById(element);
// Set the timer
var interval = setInterval(function() {
if(seconds == 0) {
if(minutes == 0) {
(el.innerHTML = "STOP!");
clearInterval(interval);
return;
} else {
minutes--;
seconds = 60;
}
}
if(minutes > 0) {
var minute_text = minutes + (minutes > 1 ? ' minutes' : ' minute');
} else {
var minute_text = '';
}
var second_text = seconds > 1 ? '' : '';
el.innerHTML = minute_text + ' ' + seconds + ' ' + second_text + '';
seconds--;
}, 1000);
}
//Start as many timers as you want
var start1 = document.getElementById('timer1');
var start2 = document.getElementById('timer2');
start1.onclick = function() {
countdown('countdown1', 0, 15);
}
start2.onclick = function() {
countdown('countdown2', 0, 10);
}
//extra button and counter
<div id='countdown1'></div>
<div id='countdown2'></div>
<input id="timer1" type="button" value="Start timer 1" />
<input id="timer2" type="button" value="Start timer 2" />
You could save the interval variable as an attribute of the countdown element. Then, at the beginning of the countdown function, check if the interval attribute has been defined for that element. If so, call clearInterval on it before starting a new interval.
clearInterval(intervalvalue)
will be helpful to .
Working code here

Changing the Background image based on time (javascript)

In the code below I change the background color based on the seconds left in the timer. I am trying to figure out if there is a way to change the background image based on the time.
I have tried to add the following:
var imgArray = ['something.jpg', 'something2.jpg'];
function changeColor(){
if (seconds <= 300 && seconds > 90) {
document.body.style.background = imgArray[0];
}
else if (seconds <= 90 && seconds > 30) {
document.body.style.background = imgArray[1];
}
else (seconds <= 30 && seconds >= 0) {
document.body.style.background = imgArray[0];
}
};
This however does not work. I am unsure what I am doing wrong. Below is my full code:
var seconds = 300; //Variables for the code below
var countdownTimer;
var colorChange; //sets up array of colors
colorChange = ['#7ed473', '#fff194', '#fa8283', 'white']
function secondPassed(){
var minutes = Math.floor(seconds/60); //takes the output of seconds/60 and makes rounds it down. 4.7 = 4, 3.7 = 3. (to keep the minutes displaying right)
var remainingSeconds = seconds % 60; //takes remainder of seconds/60 and displays it. so 270/60 = 4.5 this displays it as 30 so it becomes 4:30 instead of 4.5
if (remainingSeconds < 10) { //if remaining seconds are less than 10 add a zero before the number. Displays numbers like 09 08 07 06
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds; //displays time in the html page 5:06
document.getElementById('countdown2').innerHTML = minutes + ":" + remainingSeconds; //displays the time a second time
if (seconds == 0) {
clearInterval(countdownTimer); //keeps value at zero once it hits zero. 0:00 will not go anymore
alert("Time is Up, Try again");
}
};
function changeColor(){ //this changes the background color based on the time that has elapsed
if (seconds <= 300 && seconds > 90) { //green between 5:00 - 1:30
document.body.style.background = colorChange[0];
}
else if (seconds <= 90 && seconds > 30) { //yellow between 1:30 - 30
document.body.style.background = colorChange[1];
}
else if(seconds <= 30 && seconds >= 0){ // red between 30 - 0
document.body.style.background = colorChange[2];
}
};
function countdown(start){ //code for the button. When button is clicked countdown() calls on secondPassed() to begin count down.
secondPassed();
if (seconds != 0) { //actual code to decrement the time
seconds --;
countdownTimer = setTimeout('countdown()', 1000);
changeColor(); //calls the changeColor() function so that background changes
start.disabled = true; //disables the "start" button after being pressed
}
if (start.disabled = true){ //if one of the 'start' buttons are pressed both are disabled
start2.disabled = true;
}
};
function cdpause() { //pauses countdown
// pauses countdown
clearTimeout(countdownTimer);
};
function cdreset() {
// resets countdown
cdpause(); //calls on the pause function to prevent from automatically starting after reset
secondPassed(); //reverts back to original secondPassed() function
document.getElementById('start').disabled = false; //Enables the "start" button that has been disabled from countdown(start) function.
document.getElementById('start2').disabled = false; //enables the 'start2' button. same as above.
document.body.style.background = colorChange[3]; //Resets background color to white.
};
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="newTicket2.0.css">
<script src = "Timer2.js">
</script>
</head>
<body onload = "cdreset()">
<div id = "timerBackground">
<span id="countdown" class="timer"></span>
<div id = "timerButtons">
<input type="button" value="Start" onclick="countdown(this)" id = "start">
<input type="button" value="Stop" onclick="cdpause()">
<input type="button" value="Reset" onclick="cdreset(seconds = 300)">
</div>
</div>
<div id = "timerBackground2">
<span id="countdown2" class="timer"></span>
<div id = "timerButtons2">
<input type="button" value="Start" onclick="countdown(this)" id = "start2">
<input type="button" value="Stop" onclick="cdpause()">
<input type="button" value="Reset" onclick="cdreset(seconds = 300)">
</div>
</div>
</body>
</html>
My question is how do I get the code to change the background image rather than just changing colors?
You need to set the background with url(..) surrounding the value.
document.body.style.background = "url(" + imgArray[1] + ")";

how to make countdoun timer in java script which should not reset on page reload

i have used this code it working but when i refresh the page it reset to initial stage, i want it should continue after page reload also here is code i have used
<html>
<head>
<title>Timer</title>
</head>
<body>
<form name="counter"><input type="text" size="8" name="d2"></form>
<script>
<!--
//
var milisec=0
var seconds=30
document.counter.d2.value='30'
function display()
{
if (milisec<=0)
{
milisec=9
seconds-=1
}
if (seconds<=-1)
{
milisec=0
seconds+=1
}
else
milisec-=1
document.counter.d2.value=seconds+"."+milisec
setTimeout("display()",100)
}
display()
-->
</script>
</body>
</html>
You can save current seconds value in localStorage (or maybe sessionStorage) this is the easiest way to persist the value:
var milisec = 0
var seconds = localStorage.seconds || 30;
document.counter.d2.value = seconds;
function display() {
if (milisec <= 0) {
milisec = 9
seconds -= 1
}
if (seconds <= -1) {
milisec = 0
seconds += 1
} else milisec -= 1
localStorage.seconds = seconds;
document.counter.d2.value = seconds + "." + milisec;
if (seconds > 0 || (seconds == 0 && milisec > 0)) {
setTimeout(display, 100);
}
}
display();
Also note, that you probably want to stop interval when timer reaches 0 value, so I added seconds > 0 || (seconds == 0 && milisec > 0) part.
Demo: http://jsfiddle.net/6zL5eL2z/1/

Categories

Resources