I want to create a simple countdown timer in javascript or jquery.
I had implemented it using JS but what issue I am facing is if user refreshes the page then timer gets the refresh.
What I want is timer should not get the refresh.
Say timer is 5 min and if user refresh pages after 1 min the timer should continue to start from 4 min instead of 5 mins.
Here is code snippiet.
Its refresh the timer on page refresh.
var timeoutHandle;
function countdown(minutes) {
var seconds = 60;
var mins = minutes
function tick() {
var counter = document.getElementById("timer");
var current_minutes = mins-1
seconds--;
counter.innerHTML =
current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
if( seconds > 0 ) {
timeoutHandle=setTimeout(tick, 1000);
} else {
if(mins > 1){
// countdown(mins-1); never reach “00″ issue solved:Contributed by Victor Streithorst
setTimeout(function () { countdown(mins - 1); }, 1000);
}
}
}
tick();
}
countdown(2);
<div id="timer">2:00</div>
You just update the sessionStorage along with your counter and read it on starting the counter. Unfortunately the related snippet does not work on stackoverflow due to crossdomain policies - so here on codepen https://codepen.io/anon/pen/opNpVe
function countdown(seconds) {
seconds = parseInt(sessionStorage.getItem("seconds"))||seconds;
function tick() {
seconds--;
sessionStorage.setItem("seconds", seconds)
var counter = document.getElementById("timer");
var current_minutes = parseInt(seconds/60);
var current_seconds = seconds % 60;
counter.innerHTML = current_minutes + ":" + (current_seconds < 10 ? "0" : "") + current_seconds;
if( seconds > 0 ) {
setTimeout(tick, 1000);
}
}
tick();
}
countdown(120);
Related
I'm creating a countdown timer in minutes and seconds that that displays on the page - all seems to work fine with the bit of code I have. The only issue is when the alert box pops up I want the clock to stop counting down also.
I thought that including the return keyword under the alert pop up would resolve the issue but the clock keep ticking down.
Below is the code. Any help would be great.
window.onload = function() {
var hour = 1;
var sec = 59;
setInterval(function() {
document.getElementById("timer").innerHTML = hour + " : " + sec;
sec--;
if (sec == 0) {
hour--;
sec = 59;
}
if (hour == 1 && sec == 51)
{
alert("Stop, you have not completed the task in the alotted time");
return;
}
}, 1000);
}
To do that you need to save that Interval in a variable and then deactivate the interval with clearInterval. So your code would be like this:
window.onload = function() {
var hour = 1;
var sec = 59;
let counting_interval = setInterval(function() {
document.getElementById("timer").innerHTML = hour + " : " + sec;
sec--;
if (sec == 0) {
hour--;
sec = 59;
}
if (hour == 1 && sec == 51)
{
alert("Stop, you have not completed the task in the alotted time");
clearInterval(counting_interval); // pass the interval as the argument and it will stop to call the interval anymore
return;
}
}, 1000);
}
You need to set a timeout, not an interval. Intervals trigger until they're stopped. Timeouts happen once.
const interval = setInterval( function() {
document.getElementById("timer").innerHTML = hour + " : " + sec;
sec--;
if (sec == 0) {
hour--;
sec = 59;
}
});
const timeoutPeriod = 2 * 60 * 60 * 1000;
setTimeout(
function(){
clearInterval(interval);
alert("Stop, you have not completed the task in the alotted time");
}, timeoutPeriod
);
I'm working on a pomodoro clock, everthing is working well but when the user clicks to run the the counter more than once I get two counters working I would like to pause the counter and not start another.
function countdown(minutes) {
let seconds = 60;
let mins = minutes;
function tick() {
let current_minutes = mins-1;
seconds--;
time.innerHTML = current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
if( seconds > 0 ) {
setTimeout(tick, 1000);
} else {
if(mins > 1){
countdown(mins-1);
}
}
console.log(mins);
if (seconds === 0 && mins === 1) {
time.innerHTML = `${sessionLength}:00`;
rounds++;
console.log(rounds);
PlaySound(sound);
}
}
tick();
}
how can I accomplish this?
Why not use setInterval?
var myPomodoro = setInterval(function(){
//... run code in here every 60 seconds
}, 60000);
// stop the timer
clearInterval(myPomodoro);
I have a timer script but I am having a few issues with it. Just a day ago, it was working perfectly fine, as intended. Now, the timer no longer hides the div class when it ends. Didn't change the HTML or JavaScript code at all, but for whatever reason it no longer removes the div class.
Here is the JavaScript code:
function startTimer(duration, display) {
var timer = duration,
minutes,
seconds;
setInterval(function() {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? '0' + minutes : minutes;
seconds = seconds < 10 ? '0' + seconds : seconds;
display.textContent = minutes + ' ' + ' ' + seconds;
if (--timer < 0) {
display.textContent = 'OFFER HAS EXPIRED.';
$('.formme').css('visibility', 'hidden');
}
console.log(parseInt(seconds));
window.localStorage.setItem('seconds', seconds);
window.localStorage.setItem('minutes', minutes);
}, 1000);
}
window.onload = function() {
sec = parseInt(window.localStorage.getItem('seconds'));
min = parseInt(window.localStorage.getItem('minutes'));
if (parseInt(sec) == 0 && parseInt(min) == 0) {
$('#time').text('OFFER HAS EXPIRED.');
$('.formme').css('visibility', 'hidden');
} else {
var start = 5 * 60;
if (sec > 0 || min > 0) {
start = parseInt(min * 60) + sec;
}
// var start = 60 * 5;
display = document.querySelector('#time');
startTimer(start, display);
}
};
On top of that, I used localStorage to prevent the timer from resetting when the webpage is refreshed. However, when the timer is finished, instead of going straight to the "OFFER HAS EXPIRED" text, it counts down from 00:01 then displays the text. Can anyone help me out? Thanks in advance!
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);
}
})
so I've been tyring to debug my script for my pomodoro(tomato) clock. What I want this script to do is it will recieve input(in minutes). Right now what my script is doing is counting down by 5 instead of 1 seconds. Also it will not display the minutes like I want it too.
I made the script in a logical way to log to console and test it. What I see in the console is it displays every second, but it displays 5 seconds every second if that makes sense. Here is the jsbin: https://jsbin.com/gigohajawo/3/edit?js,consolehttps://jsbin.com/gigohajawo/3/edit?js,console
Here is the code, any help would be appreciated!!!
//makes sure the page is loaded first
$(document).ready(function() {
//global variables
//grabs text of an id and converts it to an int
var countMin = 5;
var count1 = 60;
//when button id "but" is clicked...
//while page is up, it keeps track each second that has passed
for(; countMin >=0;countMin--){
var counter1 = setInterval(function(){
//calls timer function to count down
count1 = Timer(count1,counter1,countMin);
},1000);
count1 =60;
}
//counts down
function Timer(count,counter,minutes){
count--;
//once it hits 0 seconds, the interval will stop counting
if(count <=0){
clearInterval(counter);
return count;
}
//displays the countdown
if(minutes < 10){
if(count < 10){
console.log("0:0" + count);
} else {
console.log("0:" + count);
}
}else if(minutes > 0 && minutes < 10){
if(count < 10){
console.log("0" + minutes +":0" + count);
} else {
console.log("0"+minutes+":" + count);
}
} else{
if(count < 10){
console.log(minutes+":0" + count);
} else {
console.log=minutes+":" + count;
}
}
return count;
}
});
This JSBin seems to do what you intended.
The code:
//makes sure the page is loaded first
$(document).ready(function() {
//global variables
//grabs text of an id and converts it to an int
var count1 = 120;
// Call a function every 1000 milliseconds (1 second)
var counter1 = setInterval(function() {
count1 = Timer(count1, counter1);
}, 1000);
//counts down
function Timer(count,counter){
// Decrement the seconds counter
count--;
// Get the minutes and seconds in whole numbers
var minutes = Math.floor(count / 60);
var seconds = count % 60;
// Once it hits 0 seconds, the interval will stop counting
if(count <=0){
clearInterval(counter);
}
// Pads the seconds with a 0
if (seconds < 10) {
seconds = "0" + seconds;
}
// Pads the minutes with a 0
if (minutes < 10) {
minutes = "0" + minutes;
}
//displays the countdown
console.log(minutes + ":" + seconds)
return count;
}
});
Please note:
Since you have defined count1 as a global variable you do not need to pass it into Timer
The same goes for counter1
If I was rewriting it I would do something like this:
//makes sure the page is loaded first
$(document).ready(function() {
var timeInSeconds = 120;
var timeCounter = setInterval(function() {
timeInSeconds--;
// If we hit 0 seconds clear the timer
if (timeInSeconds <= 0) {
clearInterval(timeCounter);
}
// Display the current time
displayTime();
}, 1000);
function displayTime(){
// Get the minutes and seconds in whole numbers
var minutes = Math.floor(timeInSeconds / 60);
var seconds = timeInSeconds % 60;
// Pad with zeros using the Ternary operator
seconds = (seconds < 10) ? "0" + seconds : seconds;
minutes = (minutes < 10) ? "0" + minutes : minutes;
// Display the countdown
console.log(minutes + ":" + seconds)
}
});