Javascript Second into Minutes:Seconds - javascript

I am working on a clock that needs to display seconds into a
minutes:seconds
format.
I have worked on some auxiliary functions for display, but I have never really gotten the full display. Here is some of my code:
var time = 1500;
//Must declare timeHandler as global variable for stopTimer()
var timeHandler;
//Set intial HTML to time
document.getElementById("timer").innerHTML = display;
//Timer function for start button
function timer() {
timeHandler = setInterval(function() {
if (time > 0) {
time--;
document.getElementById("timer").innerHTML = time;
}
}, 1000);
}
//Stop function for stop button
function stopTimer() {
clearTimeout(timeHandler);
}
//Timer Display
var minutes = time/60;
var second = time%60;
var display = minutes + ":" + seconds;
HTML:
<h1> Pomodoro Clock</h1>
<!--Place holder for timer-->
<div id="timer" class="circle">Timer</div>
<!--//Start Button-->
<button onclick="setTimeout(timer, 1000);">Start</button>
<!--Stop Button-->
<button onclick="stopTimer()">Stop</button>

Thie formatTime function below will take a number of seconds, and convert it to MM:SS format (including padded zeroes):
var time = 1500;
//Must declare timeHandler as global variable for stopTimer()
var timeHandler;
//Set intial HTML to time
document.getElementById("timer").innerHTML = display;
//Timer function for start button
function timer() {
timeHandler = setInterval(function() {
if (time > 0) {
time--;
document.getElementById("timer").innerHTML = formatTime(time);
}
}, 1000);
}
//Stop function for stop button
function stopTimer() {
clearTimeout(timeHandler);
}
function formatTime(seconds) {
//Timer Display
var minutes = seconds / 60;
var second = seconds % 60;
return ('0'+minutes).substr(-2) +":"+ ('0'+seconds).substr(-2);
}

first of all you have to use clearInterval, then you don't update your display every second
check this fiddle out

Related

Javascript Stopwatch. Need help to store my timer and when page refresh to keep the time and continue from there

I have a working stopwatch. When I click start button the stopwatch is starting and when I click pause button the stopwatch is paused. What I would like is when I refresh my browser to keep the current time of the stopwatch and continue from there with the same functionality. Or when I echo the stopwatch time from a database to continue from the exact time it was before is saved it.
let showTime = document.querySelector("#output");
let startTimeButton = document.querySelector("#start")
let pauseTimeButton = document.querySelector("#pause")
pauseTimeButton.style.display = "none";
let seconds = 0;
let interval = null;
const timer = () => {
seconds++;
// Get hours
let hours = Math.floor(seconds / 3600);
// Get minutes
let minutes = Math.floor((seconds - hours * 3600) / 60);
// Get seconds
let secs = Math.floor(seconds % 60);
if (hours < 10) {
hours = `0${hours}`;
}
if (minutes < 10) {
minutes = `0${minutes}`;
}
if (secs < 10) {
secs = `0${secs}`;
}
showTime.innerHTML = `${hours}:${minutes}:${secs}`;
};
startTimeButton.addEventListener("click", () => {
pauseTimeButton.style.display = "block";
startTimeButton.style.display = "none";
console.log("START TIME CLICKED");
if (interval) {
return;
}
interval = setInterval(timer, 1000);
});
// Pause function
pauseTimeButton.addEventListener("click", () => {
pauseTimeButton.style.display = "none";
startTimeButton.style.display = "block";
console.log("PAUSE TIME CLICKED");
clearInterval(interval);
interval = null;
});
<button id="start">Start</button>
<button id="pause">Pause</button>
<div id="output"></div>
You could use localStorage.
In order to save each second passed you could modify your timer function to save to localStorage:
let seconds = 0;
if (localStorage.getItem("stopwatchSeconds") != null) {
seconds = parseInt(localStorage.getItem("stopwatchSeconds"));
}
//...
const timer = () => {
//...
seconds++;
localStorage.setItem("stopwatchSeconds", seconds);
//...
};
//...
I hope this helps.
It seems like what you're looking for is localStorage. You store your stopwatch data, such as startAt, totalSeconds in the storage and when you refresh the page you can restore your stopwatch state based on the saved data: remainingTime = (startAt + totalSeconds) - currentTime
localStorage docs: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Client-side_storage#storing_simple_data_%E2%80%94_web_storage

JavaScript clearInterval() does not clear the timer

I'm trying to set up a timer that will play a sound after a certain amount of minutes have passed. The number of minutes can be set in the input field time.
The problem is clearInterval function is not working.
When I set a timer to let's say 1 minute and afterward to 2 minutes, both timers are active.
How to remove the first-timer after changing the timer to 2 minutes only the new one will play a sound?
HTML:
<input id="time" />
<button onclick="timeFunction()">
set Timer
</button>
<p id ="timer"></p>
JS:
function timeFunction() {
var minuten = document.getElementById("time").value;
var sec = minuten * 60;
var msec = sec * 1000;
document.getElementById("timer").innerHTML = "Timer set to " + minuten + " minutes";
clearInterval(inter);
var inter = setInterval(function(){
document.getElementById('gong').play(); }
,msec);
}
var inter is a variable that only exists in your timeFunction. When the function finishes, inter does not exist anymore. When clearInterval runs, inter is undefined, because you haven't assigned it a value yet.
To fix it, declare the inter variable outside of your function. This will allow it to keep a value between multiple executions of timeFunction.
var inter;
function timeFunction() {
// other code
clearInterval(inter);
inter = setInterval(function(){
document.getElementById('gong').play();
}, msec);
}
Why don't you return the interval,
function timeFunction() {
var minuten = document.getElementById("time").value;
var sec = minuten * 60;
var msec = sec * 1000;
document.getElementById("timer").innerHTML = "Timer set to " + minuten + " minutes";
return setInterval(function(){
document.getElementById('gong').play(); }
,msec);
}
then you could go,
let intervals = timeFunction();
then you can clear it like so,
clearInterval(intervals);
this way you control how many times it iterates.
If you want this to run only once clear the interval after your work has been done. So your function can be re-written like this:
function timeFunction() {
var minuten = document.getElementById("time").value;
var sec = minuten * 60;
var msec = sec * 1000;
document.getElementById("timer").innerHTML = "Timer set to " + minuten + " minutes";
var inter = setInterval(function() {
document.getElementById('gong').play();
clearInterval(inter);
}, msec);
}
EDIT
You can also return inter variable from your function so you can use clearInterval whenever your script's logic needs the interval to stop.
function timeFunction() {
var minuten = document.getElementById("time").value;
var sec = minuten * 60;
var msec = sec * 1000;
document.getElementById("timer").innerHTML = "Timer set to " + minuten + " minutes";
var inter = setInterval(function() {
document.getElementById('gong').play();
}, msec);
return inter;
}
let intv = timeFunction();
// rest of your javascript
// ...
clearInterval(intv);

JavaScript countdown timer not display button after reset

I am trying to create html5 app that have a timer. After time end in 10 second, it will display a button. Supposed to be, once user click on the button, a popup will displayed and it will count the button click in a variable and reset the timer. The process will loop again. The issue is, after user click on the button, and after the timer finished countdown for second time, the button is not displaying.
Here is the Js codes:
<!-- Timer countdown -->
<script type=text/javascript>
var clicks = 0;
function showTimer(selector, seconds)
{
var startTime = Date.now();
var interval;
function showRemaining()
{
var delta = Date.now() - startTime; // milliseconds
var deltaSeconds = delta / (1000);
if (deltaSeconds < seconds) {
// display minutes remaining
$(selector).text(Math.round(seconds - deltaSeconds));
} else {
$(selector).text(0);
clearInterval(interval);
}
}
interval = setInterval(showRemaining, 1000);
showRemaining();
}
$(document).ready(function()
{
showTimer("#countdown", 10);
});
setTimeout(function()
{
$("#proceed").show();
}, 10000);
//when click button
function onClick() {
clicks += 1;
document.getElementById("proceed").style.visibility="hidden";
alert("Getting the message");
document.getElementById("clicks").innerHTML = clicks;
showTimer("#countdown", 10);
};
</script>
This is the HTML:
<h1>Test</h1>
<br>
<p ><span id="countdown"></span><br>
Timer Here<br>
<button type="button" id="proceed" onclick="onClick()">Click</button><br>
<a id="clicks">0</a></p>
you forget to show your button again, the way you did it , it's going to hide. remove the setTimeout since you know the end of your timer and also can repeat it.
var clicks = 0;
var interval = -1;
function showTimer(selector, seconds)
{
var startTime = Date.now();
function showRemaining()
{
var delta = Date.now() - startTime; // milliseconds
var deltaSeconds = delta / (1000);
if (deltaSeconds < seconds) {
// display minutes remaining
$(selector).text(Math.round(seconds - deltaSeconds));
} else {
$(selector).text(0);
clearInterval(interval);
$("#proceed").show(); // Look at here
}
}
if( interval > -1 ) clearInterval(interval);
interval = setInterval(showRemaining, 1000);
showRemaining();
}
$(function() {
showTimer("#countdown", 10);
});
//when click button
function onClick() {
$("#proceed").hide();
alert("Getting the message");
$("#clicks").text(++clicks);
showTimer("#countdown", 10);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Test</h1>
<br>
<p >
<span id="countdown"></span><br>
Timer Here<br>
<button type="button" id="proceed" onclick="onClick()">Click</button><br>
<a id="clicks">0</a>
</p>
include jquery file link,
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js" type="text/javascript"></script>

How to stop countdown after a few rounds?

var secondsP = document.getElementById('seconds');
var btn1 = document.getElementById("btnSurrender");
var clock = null;
btn1.addEventListener("click", surrender);
function timer () {
clearInterval(clock);
var start = new Date().getTime();
clock = setInterval(function() {
var seconds = Math.round(15 - (new Date().getTime() - start) / 1000);
if (seconds >= 0) {
secondsP.textContent = seconds;
} else {
clearInterval(clock);
}
if (seconds === 0) {
}
}, 1000);
}
function surrender(){
clearInterval(clock);
secondsP.textContent = 0;
setTimeout(timer,2000);
}
timer();
setInterval(timer, 17000);
<html>
<head>
<style>
</style>
<script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
</head>
<body>
<p id="seconds">15</p>
<button id= "btnSurrender">end now</button>
</body>
</html>
I need help with my little problem. I made a stopwatch which counts down 15 seconds. After this 15 seconds, it waits two seconds and starts again. You have option to stop counting when you want to, using "end now" button (then it'll start again after 2 sec). Now, my question is: how can I make a function which is going to stop whole counting after 3/4 rounds?
You restart the clock in surrender() using the call setTimeout(timer, 2000). All you need to do is add an if statement inside that function testing a variable that controls how many times you have run the timer, and then call/not call timer() accordingly. Here is a working example of it: https://jsfiddle.net/L38q6k5d/, but just to give you an idea of how it would work:
At the top of the js file:
var timesRun = 0
var timerInterval = null;
Inside the surrender function:
timesRun += 1 // Increment it each time the timer ends
if (timesRun > 4) { // If the timer has run less than 4 times
return; // this will stop the function here, so we dont start the timer again
}
setTimeout(timer, 2000); // Reset the timer
Inside the timer function,
if (timesRun > 1) {
clearInterval(timerInterval);
return; // end the function here
}
When starting the initial timer:
timer();
timerInterval = setInterval(timer, 17000);
Complete JS:
var secondsP = document.getElementById('seconds');
var btn1 = document.getElementById("btnSurrender");
var clock = null;
var timerInterval = null;
// New Code
var numberOfTimesRun = 0; // this is where we keep track of how many times the timer has run
btn1.addEventListener("click", surrender);
function timer () {
clearInterval(clock);
// New Code
if (numberOfTimesRun > 1) {
clearInterval(timerInterval);
return; // end the function here
}
// End New Code
var start = new Date().getTime();
clock = setInterval(function() {
var seconds = Math.round(15 - (new Date().getTime() - start) / 1000);
if (seconds >= 0) {
secondsP.textContent = seconds;
} else {
clearInterval(clock);
numberOfTimesRun += 1; // so we know that 1 iteration of the timer has been completed
}
if (seconds === 0) {
}
}, 1000);
}
function surrender(){
clearInterval(clock);
secondsP.textContent = 0;
//New Code
numberOfTimesRun += 1;
if (numberOfTimesRun > 4) {
return; // end the function there
}
setTimeout(timer, 2000)
//End New Code
}
timer();
timerInterval = setInterval(timer, 17000);

Javascript Function activates before button is clicked

If requirements are met when you click the button it will display a count down timer. Problem is it displays the countdown timer BEFORE you even click the button. I'm not sure what I'm overlooking.
<input id="upgrade" type="button" value="Upgrade" onclick="timer();" />
<br><br><br><br>
<p id="countdown_timer"></p>
<script>
function display_timer(){
document.getElementById("countdown_timer").innerHTML = "<span id='countdown' class='timer'></span>";
}
</script>
<script>
var currently_upgrading = 0;
var current_ore = 398;
var current_crystal = 398;
var upgradeTime = 172801;
var seconds = upgradeTime;
function timer() {
if(currently_upgrading == 1){alert('You are already upgrading a module.');return;}
if(current_ore <= 299){alert('You need more ore.');return;}
if(current_crystal <= 299){alert('You need more crystal.');return;}
display_timer();
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = days + ":" + hours + ":" + minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Completed";
} else {
seconds--;
}
}
var countdownTimer = setInterval('timer()', 1000);
</script>
You need to move countdownTimer variable into your timer() function.
Try changing the last lines of timer() to be like this:
if (seconds == 0) {
document.getElementById('countdown').innerHTML = "Completed";
} else {
seconds--;
setTimeout(timer, 1000);
}
and remove the setInterval line.
Speaking generally, setTimeout is much preferred to setInterval, because it doesn't require a managed state (countdownTimer in your example) and is far more flexible.
Also note that passing a string as in setTimeout('timer()', 1000) is obsolete, just pass a function: setTimeout(timer, ...).
This line
var countdownTimer = setInterval('timer()', 1000);
will execute 1 second after the page loads as well as on the button click and this calls the display_timer function.
you have called it in setInterval function, so it will starts immediately , because setInterval function runs after page loads and not on click and setInterval uses your function

Categories