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)
}
});
Related
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 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);
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/
Suppose you wanted to set a timer to whatever time you want will be displayed in the form 00:00:00 minutes, seconds, and hundredths. How would you go about doing so? Please any help is greatly appreciated.
Here is the link in JSFiddle:
https://jsfiddle.net/mxpuejvz/2/
function decrement(){
var time = 600;
var mins = parseInt((time / 100) / 60);
var secs = parseInt((time / 100) % 60);
var hundredths = parseInt(time % 100);
if(mins < 10) {
mins = "0" + mins;
}
if(secs < 10) {
secs = "0" + secs;
}
if(hundredths < 10) {
hundredths = "0" + hundredths;
}
document.getElementById("output").innerHTML = mins + ":" + secs + ":" + hundredths;
if (hundredths === 0){
if(time ===0){
clearInterval(countdownTimer);
document.getElementById("output").innerHTML = "Time's Up.";
}else{
time--;
}
var countdownTimer = setInterval('decrement()', 10)
}
}
}
Three issues appear to need attention.
"time to go" needs to be stored outside the screen update function and decremented or calculated each time the screen is updated.
using parseInt to convert numbers to integer numbers is regarded as a hack by some. Math.floor() or integer calculation can be alternatives.
Timer call backs are not guaranteed to made exactly on time: counting the number of call backs for a 10msec time does not give the number of 1/100ths of elapsed time.
The following code is an example of how it could work, minus any pause button action.
var countdownTimer;
var endTime;
var counter = 0; // ** see reply item 3. **
function startCountDown( csecs) // hundredths of a second
{ endTime = Date.now() + 10*csecs; // endTime in millisecs
decrement();
countdownTimer = setInterval(decrement, 10);
counter = 0; // testing
}
function decrement()
{ var now, time, mins, secs, csecs, timeStr;
++ counter; // testing
now = Date.now();
if( now >= endTime)
{ time = 0;
timeStr = "Times up! counter = " + counter;
clearInterval( countdownTimer);
}
else
{ time = Math.floor( (endTime - now)/10); // unit = 1/100 sec
csecs = time%100;
time = (time-csecs)/100; // unit = 1 sec
secs = time % 60;
mins = (time-secs)/60; // unit = 60 secs
timeStr =
( (mins < 10) ? "0" + mins : mins) + ":" +
( (secs < 10) ? "0" + secs : secs) + ":" +
( (csecs < 10) ? "0" + csecs : csecs);
}
document.getElementById("output").innerHTML=timeStr;
}
The argument to startCountDown gives the number of 1/100ths of second for the count down. If the counter result is the same as the argument,try swapping browser tabs and back again during the countdown.
HTML to test:
<button type="button" onclick="startCountDown(600)">start</button>
<div id="output">
</div>