I have a simple question. I want to make this code work with the Reset time button when the time is start again from 30 min delete the ( You are Ready! ) and start the time
var seconds = 30;
function secondPassed() {
var minutes = Math.round((seconds - 30) / 60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "You are Ready!";
} else {
seconds--;
}
}
var countdownTimer = setInterval('secondPassed()', 1000);
<span id="countdown" class="timer">
Reset time
I created a new function to reset the seconds and restart the timer and linked it to the button. I have also isolated at the start of the js code the variables that will count the seconds and hold the reference to the Interval.
is this what you are looking for?
var seconds;
var countdownTimer;
function startTimer() {
if (!seconds || seconds == 0) {
seconds = 30;
clearInterval(countdownTimer);
countdownTimer = setInterval(secondPassed, 1000)
secondPassed();
}
}
function secondPassed() {
var minutes = Math.round((seconds - 30) / 60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "You are Ready!";
} else {
seconds--;
}
}
startTimer();
<html>
<body>
<div>
<span id="countdown" class="timer"></span>
</div>
Reset time
</body>
</html>
Here create a separate function where after clicking - it disables the button, sets the timer, and changes button text.
In secondPassed method, if seconds == 0, it enables the button, so that you can start count down again.
var seconds = 30;
var countdownTimer;
function secondPassed() {
var minutes = Math.round((seconds - 30) / 60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0)
{
clearInterval(countdownTimer);
document.getElementById('reset').disabled = false;
document.getElementById('countdown').innerHTML = "You are Ready!";
} else
{
seconds--;
}
}
function start(){
seconds = 30;
document.getElementById('reset').innerHTML = "Reset";
document.getElementById('reset').disabled = true;
countdownTimer = setInterval('secondPassed()', 1000);
}
//on load call
start();
<div>
<span id="countdown" class="timer"/>
</div>
<button id="reset" onclick="start()">
Start
</button>
Let's assume something quite basic, like the following:
<div>00:00</div>
<button>Reset</button>
Below is an approach you could take, fully-commented.
// We'll start by getting a couple element references
const label = document.querySelector("div");
const button = document.querySelector("button");
// Next, we'll bind-up the click handler for the button
button.addEventListener("click", () => {
// When the user clicks the button, we'll set the time
// limit to 30 minutes and proceed
let timer = 60 * 30;
// Disable the button to prevent further clicks
button.disabled = true;
button.dataset.default = button.textContent;
button.textContent = "Now counting down!";
// Let's setup some code that will be executed every second
button.interval = setInterval(() => {
// This decimal will be a number like 29.9521
const decimal = timer / 60;
// We'll convert 29.9521 into 29, for 29 minutes
const wholeMinute = Math.floor(decimal);
// Next, we'll take the .9521 and multiply by 60 for seconds
const wholeSecond = Math.round(60 * (decimal - wholeMinute));
// We'll pad both of the numbers so they always have a leading 0
const lblMin = wholeMinute.toString().padStart(2, 0);
const lblSec = wholeSecond.toString().padStart(2, 0);
// As long as we aren't out of seconds
if (timer >= 0) {
// Reduce the timer by 1 second
timer = timer - 1;
// And print the new label on our label element
label.textContent = `${ lblMin }:${ lblSec }`;
// Then return, so we don't execute what comes next
return;
}
// If we made it this far, our timer ran out
// Start by enabling the button
button.disabled = false;
// Restore the original text of the button
button.textContent = button.dataset.default;
// And clear our interval, as it is no longer needed
clearInterval(button.interval);
// Our interval will 'tick' once every second (1000 milliseconds)
}, 1000);
});
Related
I'm working on a simple pomodoro clock project using JQuery. I've gotten to where I can get the time to display and countdown the way it should but I am having issues when the timer gets to zero. I can't seem to get the clock to stop and to display 00:00 and then start the break timer. Instead I'm getting a garbage number when the timer is over. When the session time gets to 0 the clock should clear and start the break timer.
I have created a codepen for this project so you can visualize the issue. https://codepen.io/nick_kinlen/full/Bdgdqp/
var working = true;
var breaking = false;
var workTime = .10;
var breakTime = 32.00;
var minutes;
var seconds;
$(document).ready(function(){
$('#start').click(function(){
initializeClock('#clock', minutes, seconds);
});
workTime = workTime * 60;
breakTime = breakTime * 60;
});
function initializeClock(id, minutes, seconds){
// set up initial display of clock
var clock = $('#clock');
clock.text(workTime);
// update time every second, if time is 0 stop timer
var timeInterval = setInterval(function(){
clock.text(minutes, seconds);
if(working === true) {
if(updateClock(minutes) < 0 && updateClock(seconds) < 0){
clearInterval(timeInterval);
working = false;
breaking = true;
alert('Hey this block of code is executing!');
}
else if(breaking === true){
if(updateClock(minutes) === 0 && updateClock(seconds) === 0){
clearInterval(timeInterval);
breaking = false;
working = true;
}
}
}
}, 1000);
}
function updateClock(time){
// subtract time from current time,
workTime--;
minutes = Math.floor(workTime % 3600 / 60);
seconds = workTime % 60;
// Adds a 0 in front of single digit minutes/seconds
minutes = ('0' + minutes).slice(-2);
seconds = ('0' + seconds).slice(-2);
// update clock
$('#clock').text(minutes + ':' + seconds);
console.log(minutes, seconds);
// If the block is on break time
if(breaking){
var minutes = Math.floor(breakTime % 3600 / 60);
var seconds = breakTime % 60;
breakTime--;
minutes = ('0' + minutes).slice(-2);
seconds = ('0' + seconds).slice(-2);
$('#clock').text(minutes + ':' + seconds);
}
}
// Add/subtract time to break
$('#subtractBreakMinute').click(function(){
if(breakTime > 0) {
breakTime -= 1;
$('#breakDisplay').text(breakTime);
}
})
$('#addBreakMinute').click(function(){
if(breakTime < 59) {
breakTime += 1;
$('#breakDisplay').text(breakTime);
}
})
// Add/subtract time to workTime
$('#subtractSessionMinute').click(function(){
if(workTime > 0) {
workTime -= 1;
$('#sessionDisplay').text(workTime);
}
})
$('#addSessionMinute').click(function(){
if(workTime < 59) {
workTime += 1;
$('#sessionDisplay').text(workTime);
}
})
I am designing a javaScript countdown for 3 hours using the below code
<div id="timer"></div>
<script type="text/javascript">
var count = 10800;
var counter = setInterval(timer, 1000); //1000 will run it every 1 second
function timer() {
count = count - 1;
if (count == -1) {
clearInterval(counter);
return;
}
var seconds = count % 60;
var minutes = Math.floor(count / 60);
var hours = Math.floor(minutes / 60);
minutes %= 60;
hours %= 60;
document.getElementById("timer").innerHTML = hours + "hours " + minutes + "minutes and " + seconds + " seconds left to complete this transaction"; // watch for spelling
}
</script>
but the only issue I am having here is whenever I refresh the page the countdown starts all over again. I want it to resume from where it stopped.
You need to store the data into some persistent storage method, such as cookies, the browsers localStorage, or write data out to an external data source (such as a database through an API). Otherwise the session data is lost between browser refreshes.
For example, if you wanted to use localStorage:
<script type="text/javascript">
// properties
var count = 0;
var counter = null;
window.onload = function() {
initCounter();
};
function initCounter() {
// get count from localStorage, or set to initial value of 1000
count = getLocalStorage('count') || 1000;
counter = setInterval(timer, 1000); //1000 will run it every 1 second
}
function setLocalStorage(key, val) {
if (window.localStorage) {
window.localStorage.setItem(key, val);
}
return val;
}
function getLocalStorage(key) {
return window.localStorage ? window.localStorage.getItem(key) : '';
}
function timer() {
count = setLocalStorage('count', count - 1);
if (count == -1) {
clearInterval(counter);
return;
}
var seconds = count % 60;
var minutes = Math.floor(count / 60);
var hours = Math.floor(minutes / 60);
minutes %= 60;
hours %= 60;
document.getElementById("timer").innerHTML = hours + "hours " + minutes + "minutes and " + seconds + " seconds left to complete this transaction"; // watch for spelling
}
</script>
<div id="timer"></div>
You can try it out here: https://jsfiddle.net/rcg4mt9x/
counter that i can change time to remain if i want from db
i have a time stamp in table in db that maybe change
now i want for example every 30sec check that and if changed my down-counter changing
my js script is:
<script>
var seconds = 100;
function secondPassed() {
var minutes = Math.round((seconds - 30)/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = '0' + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ':' + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = 'Times Up!';
document.getElementById('passage_text').disabled = true;
} else {
seconds--;
}
}
var countdownTimer = setInterval('secondPassed()', 1000);
</script>
Try changing this:
var countdownTimer = setInterval('secondPassed()', 1000);
to this:
var countdownTimer = setInterval(secondPassed, 1000);
What isn't working in your case, exactly?
BTW: Try caching reference on frequently used DOM element. See this alternative using much simpler code for formatting your time.
var display = document.getElementById('countdown');
var seconds = 100, timer;
function secondPassed() {
if ( --seconds == 0 ) {
window.clearInterval( timer );
// your code here executing when count down has finished ...
} else {
display.innerHTML = Math.floor( seconds / 60 ) + ':' + String( "0" + ( seconds % 60 ) ).substr( -2 );
}
}
timer = window.setInterval( secondPassed, 1000 );
I have borrowed some JS code to help me create a timer for 65 seconds. My JS knowledge is basic but I managed to modify the script to work the way I want it to. However when I click on the play button the timer speeds up from the second round onwards.
HTML:
<div id="rightCol">
<span id="countdown" class="timer">Timer About to Start! </span>
<div>
<input type="button" value="Play" id="play">
</div>
</div>
JS:
var seconds = 65;
function secondPassed() {
var minutes = Math.round((seconds - 30)/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Time's Up!";
document.getElementById("passage_text").disabled = true;
} else {
seconds--;
}
}
var countdownTimer = setInterval('secondPassed()', 1000);
$("#play").click(function(){
seconds = 65;
var countdownTimer = setInterval('secondPassed()', 1000);
$('#passage_text').attr('disabled', false).focus();
$("#passage_text").val('');
});
I read some of the other answers similar to mine Count down timer speeds up but I don't fully understand how the secondPassed() function works to fix it.
You need to clear interval on play functionality too and make countdownTimer global. Also it's better to pass function handler to setInterval instead of string as this will work as eval function and not recommended
var seconds = 65;
var countdownTimer = null; // make it global
function secondPassed() {
var minutes = Math.round((seconds - 30)/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Time's Up!";
document.getElementById("passage_text").disabled = true;
} else {
seconds--;
}
}
countdownTimer = setInterval(secondPassed, 1000); // removed var and passing handler instead of string.
$("#play").click(function(){
seconds = 65;
clearInterval(countdownTimer); // clear interval
countdownTimer = setInterval(secondPassed, 1000); // removed var to use global countdownTimer variable
$('#passage_text').attr('disabled', false).focus();
$("#passage_text").val('');
});
See my JS comments above
I am making a speed dating timer that counts down from 3 minutes to 0, shows a "move on to next date" message, and then repeats.
I have been able to get the timer to count down to 0, and then restart after the interval I've set, but for some reason it will not display the message. My code is as follows
function countdown(element, minutes, seconds) {
// set time for the particular countdown
var time = minutes*60 + seconds;
var interval = setInterval(function() {
var el = document.getElementById(element);
// if the time is 0 then end the counter
if(time == 0) {
el.innerHTML = "Move on to next date...";
clearInterval(interval);
setTimeout(function() {
countdown('clock', 3, 0);
}, 2000);
}
var minutes = Math.floor( time / 60 );
if (minutes < 10) minutes = "0" + minutes;
var seconds = time % 60;
if (seconds < 10) seconds = "0" + seconds;
var text = minutes + ':' + seconds;
el.innerHTML = text;
time--;
}, 1000);
}
countdown('clock', 3, 0);
just try this code i have fixed it for you
<html>
<head>
<Script>
function countdown(element, minutes, seconds) {
// set time for the particular countdown
var time = minutes*60 + seconds;
var interval = setInterval(function() {
var el = document.getElementById('element');
// if the time is 0 then end the counter
if(time == 0) {
setTimeout(function() {
el.innerHTML = "Move on to next date...";
}, 10);
clearInterval(interval);
setTimeout(function() {
countdown('clock', 0, 5);
}, 2000);
}
var minutes = Math.floor( time / 60 );
if (minutes < 10) minutes = "0" + minutes;
var seconds = time % 60;
if (seconds < 10) seconds = "0" + seconds;
var text = minutes + ':' + seconds;
el.innerHTML = text;
time--;
}, 1000);
}
countdown('clock', 0, 5);
</script>
</head>
<body>
<p id="element">elelelelel</p>
</body>
</html>
You're falling through into the "set the time" part again after the 'set the text' part. It is updating the text, but then overwriting it with "00:00".
You should insert a return statement to stop it continuing, or wrap the clock part in an else block.
function countdown(element, minutes, seconds) {
// set time for the particular countdown
var time = minutes*60 + seconds;
var interval = setInterval(function() {
var el = document.getElementById(element);
// if the time is 0 then end the counter
if (time <= 0) {
var text = "hello";
el.innerHTML = text;
setTimeout(function() {
countdown('clock', 0, 5);
}, 2000);
clearInterval(interval);
return;
}
var minutes = Math.floor( time / 60 );
if (minutes < 10) minutes = "0" + minutes;
var seconds = time % 60;
if (seconds < 10) seconds = "0" + seconds;
var text = minutes + ':' + seconds;
el.innerHTML = text;
time--;
}, 1000);
}
countdown('clock', 0, 5);
See fiddle: http://jsfiddle.net/aTDJY/
I got this to work by changing
innerHTML to innerText
In my example the clock is just a div. If you are using textbox you need to use to use value.
Here's my complete solution.
<html>
<head>
<script type="text/javascript">
function countdown(element, minutes, seconds) {
// set time for the particular countdown
var time = minutes*60 + seconds;
var interval = setInterval(function() {
var el = document.getElementById(element);
// if the time is 0 then end the counter
if(time == 0) {
el.innerText = "Move on to next date...";
clearInterval(interval);
setTimeout(function() {
countdown('clock', 3, 0);
}, 10);
}
var minutes = Math.floor( time / 60 );
if (minutes < 10) minutes = "0" + minutes;
var seconds = time % 60;
if (seconds < 10) seconds = "0" + seconds;
var text = minutes + ':' + seconds;
el.innerText = text;
time--;
}, 10);
}
countdown('clock', 3, 0);
</script>
</head>
<body>
<h1>Clock</h1>
<div id="clock"/>
</body>
</html>
I will do it like this instead
$(document).ready(function(){
setInterval(UpdateTime(), 1000);
});
var interval = 3*60; // 3 minutes
function updateTime(){
interval --;
if(interval == 0)
{
$(element).val("Move on to next date...");
var interval = 3*60;
}
else
{
$(element).html(interval + " seconds left");
}
}