I made a count down timer but would like to add extra minutes to it with a button.
I made a function to add 1 minute to the timer but i can't get it to add the minute. How would I achieve this?
I commented out the code since it breaks the rest of my code.
The add1Minute() function should add 1 minute to the timer when it isn't running.
I tried doing this by adding 1 to the variable and after that add it to the timer.
let countdown;
create();
function create() {
const mainDiv = document.createElement("div");
document.body.appendChild(mainDiv);
const timeDiv = document.createElement("div");
timeDiv.setAttribute("id", "timeText");
timeDiv.innerHTML = "25:00";
mainDiv.appendChild(timeDiv);
const startButton = document.createElement("button");
startButton.setAttribute("class", "button");
//startButton.addEventListener ("id", "startButton");
startButton.addEventListener("click", startTimer);
startButton.innerHTML = "start";
mainDiv.appendChild(startButton);
const restartButton = document.createElement("button");
restartButton.setAttribute("class", "button");
restartButton.addEventListener("click", restartTimer);
restartButton.innerHTML = "restart";
mainDiv.appendChild(restartButton);
/*
const minute1Button = document.createElement("button");
minute1Button.setAttribute("class", "button");
startButton.addEventListener ('click', add1Minute);
minute1Button.innerHTML = "+ 1 minute";
mainDiv.appendChild(minute1Button);
const minute10Button = document.createElement("button");
minute10Button.setAttribute("class", "button");
minute10Button.addEventListener ('click',add10Minute);
minute10Button.innerHTML = "+ 10 minutes";
mainDiv.appendChild(minute10Button);
*/
}
//startTimer()
function startTimer(sMin1) {
let sMin = 0.15;
function add1Minute(sMin) {
sMin + 1;
return sMin;
}
//if(sMin1 != null){
//sMin + sMin1;
//}
let time = sMin * 60;
countdown = setInterval(update, 1000);
function update() {
let min = Math.floor(time / 60);
let sec = time % 60;
sec = sec < 10 ? "0" + sec : sec;
timeText.innerHTML = min + ":" + sec;
time--;
min == 0 && sec == 0 ? clearInterval(countdown) : countdown;
}
}
//function add1Minute(sMin){
// sMin + 1;
// return sMin1;
//}
function add10Minute() {}
function restartTimer() {
clearInterval(countdown);
document.body.innerHTML = "";
create();
}
try:
let sMin = 0.15;
function add1Minute() {
if (!countdown) {
sMin += 1;
}
}
function startTimer() {
let time = sMin * 60;
countdown = setInterval(update, 1000);
function update() {
let min = Math.floor(time / 60);
let sec = time % 60;
sec = sec < 10 ? "0" + sec : sec;
timeText.innerHTML = min + ":" + sec;
time--;
min == 0 && sec == 0 ? clearInterval(countdown) : countdown;
}
}
Related
Three problems, my start button starts more than one timer at the same time instead of only once for multiple clicks to start. Second, my stop button doesn't work. and my reset button, changes the text but doesnt stop the timer. Here's my code:
function stopTimer(timer) {
clearInterval(timer);
}
function resetTimer(duration, display) {
var timer = duration,
minutes, seconds;
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;
}
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;
// Beep when counter reaches zero
if (--timer < 0) {
timer = duration;
var context = new AudioContext();
var oscillator = context.createOscillator();
oscillator.type = "sine";
oscillator.frequency.value = 800;
oscillator.connect(context.destination);
oscillator.start();
setTimeout(function() {
oscillator.stop();
}, 100);
}
}, 1000);
}
var time_in_seconds = 5;
display = document.querySelector('#time');
document.getElementById("start").addEventListener("click", function() {
startTimer(time_in_seconds, display);
});
document.getElementById("stop").addEventListener("click", function() {
stopTimer(timer);
});
document.getElementById("reset").addEventListener("click", function() {
resetTimer(time_in_seconds, display);
});
<html>
<body>
<div id="time">00:10</div>
<button id="start">Start</button>
<button id="stop">Stop</button>
<button id="reset">Reset</button>
<script>
</script>
</body>
</html>
var duration = 5;
var timer_id = null;
var timer_seconds = duration;
var timer_active = 0;
var display = document.querySelector('#time');
function BeepOnce() {
timer_seconds = duration;
var context = new AudioContext();
var oscillator = context.createOscillator();
oscillator.type = "sine";
oscillator.frequency.value = 800;
oscillator.connect(context.destination);
oscillator.start();
setTimeout(function() {
oscillator.stop();
}, 100);
}
function UpdateDisplay() {
var minutes = parseInt(timer_seconds / 60, 10);
var seconds = parseInt(timer_seconds % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
}
function TimerReset() {
timer_seconds = duration;
timer_active = 1;
UpdateDisplay();
}
function TimerStart() {
timer_seconds = duration;
timer_active = 1;
UpdateDisplay();
}
function TimerStop() {
timer_active = 0;
/*clearInterval(timer_id);*/
}
function TimerInit() {
UpdateDisplay();
var fun1 = function() {
if (timer_active) {
// Beep at Zero Seconds
if (--timer_seconds < 0) {
BeepOnce();
TimerReset();
}
// Countdown
else {
UpdateDisplay();
}
}
}
//called timer every second
timer_id = setInterval(fun1, 1000);
}
TimerInit();
document.getElementById("start").addEventListener("click", function() {
TimerStart();
});
document.getElementById("stop").addEventListener("click", function() {
TimerStop();
});
document.getElementById("reset").addEventListener("click", function() {
TimerReset();
});
<html>
<body>
<div id="time">00:10</div>
<button id="start">Start</button>
<button id="stop">Stop</button>
<button id="reset">Reset</button></body>
</html>
I am in trouble. I did countdown timer code in java script but when I refresh the page timer is reset so how to fix this problem
Here is my code.
var min = 1;
var sec = 59;
var timer;
var timeon = 0;
function ActivateTimer() {
if (!timeon) {
timeon = 1;
Timer();
}
}
function Timer() {
var _time = min + ":" + sec;
document.getElementById("Label1").innerHTML = _time;
if (_time != "0:0") {
if (sec == 0) {
min = min - 1;
sec = 59;
} else {
sec = sec - 1;
}
timer = setTimeout("Timer()", 1000);
} else {
window.location.href = "page2.html";
}
}
<BODY onload="Timer();">
<div id="Label1"> </div>
</BODY>
This approach uses localStorage and does not Pause or Reset the timer on page refresh.
<p id="demo"></p>
<script>
var time = 30; // This is the time allowed
var saved_countdown = localStorage.getItem('saved_countdown');
if(saved_countdown == null) {
// Set the time we're counting down to using the time allowed
var new_countdown = new Date().getTime() + (time + 2) * 1000;
time = new_countdown;
localStorage.setItem('saved_countdown', new_countdown);
} else {
time = saved_countdown;
}
// Update the count down every 1 second
var x = setInterval(() => {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the allowed time
var distance = time - now;
// Time counter
var counter = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = counter + " s";
// If the count down is over, write some text
if (counter <= 0) {
clearInterval(x);
localStorage.removeItem('saved_countdown');
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script>
Javascript is client-sided. It will reset on reload or any other thing.
A simple solution to your problem might be html5 storage, or session storage.
https://www.w3schools.com/html/html5_webstorage.asp
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
Hope this helped!
You're looking for window.localStorage. Something like this should work:
<script language="javascript" type="text/javascript">
var min = 1;
var sec = 59;
var timer;
var timeon = 0;
function ActivateTimer() {
//Don't activate if we've elapsed.
if(window.localStorage.getItem('elapsed') != null)
return;
if (!timeon) {
timeon = 1;
Timer();
}
}
function Timer() {
var _time = min + ":" + sec;
document.getElementById("Label1").innerHTML =_time;
if (_time != "0:0") {
if (sec == 0) {
min = min - 1;
sec = 59;
} else {
sec = sec - 1;
}
timer = setTimeout("Timer()", 1000);
}
else {
window.localStorage.setItem('elapsed', true);
window.location.href = "page2.html";
}
}
</script>
I am building an aptitude test with a timer. i want to show a div of time out on countdown finish. and is it possible to show a **Lean Modal Popup ** box on countdown finish. Please help!!!. Heres the code
Javascript
<script language="JavaScript" type="text/javascript">
function CountDownTimer(duration, granularity) {
this.duration = duration;
this.granularity = granularity || 1000;
this.tickFtns = [];
this.running = false;
}
CountDownTimer.prototype.start = function() {
if (this.running) {
return;
}
this.running = true;
var start = Date.now(),
that = this,
diff, obj;
(function timer() {
diff = that.duration - (((Date.now() - start) / 1000) | 0);
if (diff > 0) {
setTimeout(timer, that.granularity);
} else {
diff = 0;
that.running = false;
}
obj = CountDownTimer.parse(diff);
that.tickFtns.forEach(function(ftn) {
ftn.call(this, obj.minutes, obj.seconds);
}, that);
}());
};
CountDownTimer.prototype.onTick = function(ftn) {
if (typeof ftn === 'function') {
this.tickFtns.push(ftn);
}
return this;
};
CountDownTimer.prototype.expired = function() {
return !this.running;
};
CountDownTimer.parse = function(seconds) {
return {
'minutes': (seconds / 60) | 0,
'seconds': (seconds % 60) | 0
};
};
window.onload = function () {
var display = document.querySelector('#time'),
timer = new CountDownTimer(5),
timeObj = CountDownTimer.parse(5);
format(timeObj.minutes, timeObj.seconds);
timer.onTick(format);
document.querySelector('button').addEventListener('click', function () {
timer.start();
});
function format(minutes, seconds) {
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ':' + seconds;
}
if(display.textContent == 0){
document.querySelector("#div1").style.display="block";
}
};
</script>
Html
<button>Start Count Down</button>
<div>Registration closes in <span id="time"></span> minutes!</div>
div to show
<div id="div1" style="display:none;" ><p>Hello</p></div>
Ok, so the thing is, you have this piece of javascript code:
window.onload = function () {
var display = document.querySelector('#time'),
timer = new CountDownTimer(5),
timeObj = CountDownTimer.parse(5);
format(timeObj.minutes, timeObj.seconds);
timer.onTick(format);
document.querySelector('button').addEventListener('click', function () {
timer.start();
});
function format(minutes, seconds) {
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ':' + seconds;
}
if(display.textContent == 0){
document.querySelector("#div1").style.display="block";
}
At the bottom, you have an "if" statement.
Just move that if statement into the "format" function as follow:
window.onload = function () {
var display = document.querySelector('#time'),
timer = new CountDownTimer(5),
timeObj = CountDownTimer.parse(5);
format(timeObj.minutes, timeObj.seconds);
timer.onTick(format);
document.querySelector('button').addEventListener('click', function () {
timer.start();
});
function format(minutes, seconds) {
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ':' + seconds;
console.log(display.textContent);
if(display.textContent == "00:00") {
document.querySelector("#div1").style.display="block";
}
}
};
Your code, the way it currently is, is not performing the check on every tick.
Also, you are not checking against "0". The value should be "00:00"
Of course, you can move the check to show the div into the tick event, but that is totally up to you.
I am new in javascript, I want to create a countdown timer with localStorage which starts from given time and end to 00:00:00, but it's not working,
When I am running my code it is showing value "1506".
Here is my code
<script type="text/javascript">
if (localStorage.getItem("counter")) {
var CurrentTime = localStorage.getItem("counter");
}
else {
var Hour = 3;
var Minute = 25;
var Second = 60;
var CurrentTime = Hour.toString() + ":" + Minute.toString() + ":" + Second.toString();
}
function CountDown() {
document.getElementById('lblDuration').innerHTML = CurrentTime;
Second--;
if (Second == -1) {
Second = 59;
Minute--;
}
if (Minute == -1) {
Minute = 59;
Hour--;
}
localStorage.setItem("counter", CurrentTime);
}
var interval = setInterval(function () { CountDown(); }, 1000);
</script>
you need to declare variables Hour, Minute, Second, CurrentTime out side if else block. In this case they are not in function CountDown() scope.
you are not setting CurrentTime = Hour.toString() + ":" + Minute.toString() + ":" + Second.toString(); after localStorage.setItem("counter", CurrentTime);
var Hour = 3;
var Minute = 25;
var Second = 60;
var CurrentTime = Hour.toString() + ":" + Minute.toString() + ":" + Second.toString();
function CountDown() {
document.getElementById('lblDuration').innerHTML = CurrentTime;
Second--;
if (Second == -1) {
Second = 59;
Minute--;
}
if (Minute == -1) {
Minute = 59;
Hour--;
}
CurrentTime = Hour.toString() + ":" + Minute.toString() + ":" + Second.toString();
}
setInterval(function () {
CountDown();
}, 1000);
<div id="lblDuration"></div>
When localStorage is available you don set the values for Hour, Minute and Second. So when the countdown function executed it finds Second to be undefined and the statement Second-- converts Second to NaN.
To fix it just initialize the Hour, Minute and Second Variable.
I 've refactored your code a little bit hope it helps:
function CountDown() {
var currentTime = getCurrentTime();
printCurrentTime(currentTime)
currentTime.second--;
if (currentTime.second == -1) {
currentTime.second = 59;
currentTime.minute--;
}
if (currentTime.minute == -1) {
currentTime.minute = 59;
currentTime.hour--;
}
setCurrentTime(currentTime);
}
function setCurrentTime(newCurrentTime){
if(localStorage) localStorage.setItem("counter", JSON.stringify(newCurrentTime));
else setCurrentTime.storage = newCurrentTime;
}
function getCurrentTime(){
var result = localStorage ? localStorage.getItem("counter") : setCurrentTime.storage;
result = result || {hour:3, minute:25, second:60};
if (typeof(result) === "string")result = JSON.parse(result);
result.toString = function(){
return result.hour + ":" + result.minute + ":" + result.second;
}
return result;
}
function printCurrentTime(currentime){
var domTag = document.getElementById('lblDuration');
if(domTag) domTag.innerHTML = currentime.toString();
else console.log(currentime);
}
setInterval(function () { CountDown(); }, 1000);
Il try to explain this as simple as I can.
I'm trying to make a timer app for practice. User should be abble to add a new Object, wich will be a timer + stop/start buttons.
At this point, its working with one object, but when I create another object, the old one stops working(i belive it loses the pointer to it, or somthing like that), and the new one works.
Dont worry, about the buttons functionality,thats not important, all I want to understand how do I save the object, after a new one is created.
here is JS:
var startTime = 0;
var itemNum = 0;
var obName;
var arrayForTimers = [];
function timerObject(obName) {
this.nameField = "start";
this.classField = "timer";
this.block = " ";
this.obName = obName;
this.startButton = " ";
this.stopButton = " ";
this.placeholder = document.getElementsByClassName("timer-placeholder")[0];
this.addBlock = function () {
this.block = document.createElement("DIV");
this.block.className = this.classField;
this.block.className += " " + this.obName;
this.placeholder.appendChild(this.block);
}
this.renderTime = function () {
this.startTime = startTime;
this.endTime = new Date();
// time difference in ms
this.timeDiff = this.endTime - this.startTime;
// strip the miliseconds
this.timeDiff /= 1000;
// get seconds
this.seconds = Math.round(this.timeDiff % 60);
// remove seconds from the date
this.timeDiff = Math.floor(this.timeDiff / 60);
// get minutes
this.minutes = Math.round(this.timeDiff % 60);
// remove minutes from the date
this.timeDiff = Math.floor(this.timeDiff / 60);
// get hours
this.hours = Math.round(this.timeDiff % 24);
this.block.innerHTML = this.hours + " h " + this.minutes + " min " + this.seconds + " sec";
// window.setInterval('this.obName.renderTime()',1000);// Uncomment if you want to test your PCs limit
}
this.renderButtons = function () {
var timePassed;
//this.parentTimer = document.getElementsByClassName("timer "+this.obName)[0];
this.startButton = document.createElement("INPUT");
this.startButton.setAttribute("type", "button");
this.startButton.setAttribute("value", "start");
this.startButton.className = "start " + this.obName;
this.stopButton = document.createElement("INPUT");
this.stopButton.setAttribute("type", "button");
this.stopButton.setAttribute("value", "stop");
this.stopButton.className = "stop " + this.obName;
this.placeholder.insertBefore(this.startButton, this.block);
this.placeholder.insertBefore(this.stopButton, this.block);
this.startButton.addEventListener("click", function () {
//if (this.hours === 0 && this.minutes === 0 && this.seconds === 0){
this.startTime = new Date();
// }
tm = window.setInterval('obName.renderTime()', 1000);
})
this.stopButton.addEventListener("click", function () {
window.clearInterval(tm);
//timePassed = this.endTime - this.startTime;
//endTime = new Date();
// timePassed = endTime - startTime;
})
//give listener to clear and start interval
}
};
function createNewTimer() {
obName = document.getElementById("ObName").value;
if (obName !== "") {
obName = new timerObject(obName);
obName.addBlock();
obName.renderButtons();
startTime = new Date();
obName.renderTime();
//arrayForTimers.push(obName);
//window.setInterval('obName.renderTime()',1000);
} else {
document.getElementById("ObName").value = "Fill me";
}
};
Here is a Js Fiddle http://jsfiddle.net/3qxoea52/4/
P.S. sorry for my grammar, not my native languege.
Thanks.
The problem is here
tm = window.setInterval('obName.renderTime()', 1000);
This means that when you click any of the start buttons it will always start the object currently associated with obName.
Also, you only have a single global variable tm to store the timer, so when you do
window.clearInterval(tm);
It is clearing whichever timer was last set.
And you also have a single global startTime, which is causing all of the timers to reset whenever you create a new timer.
Another problem is that you have nothing to store the time when you stop each timer, so if you stop then restart it, it will not continue at the same point.
You can fix these problems by:
using self = this to create a stable reference to the object
use function.bind to make sure an event handler will be bound to the right timer object
add a property this.startDiff so that the time is saved when you stop then restart the clock
make tm a local variable within the TimerObject
set this.startTime within the object instead of outside it.
-- as in the code below (jsfiddle)
function TimerObject(obName) {
var self = this,
tm;
this.startTime = new Date();
this.startDiff = 0;
this.nameField = "start";
this.classField = "timer";
this.block = " ";
this.obName = obName;
this.startButton = " ";
this.stopButton = " ";
this.placeholder = document.getElementsByClassName("timer-placeholder")[0];
this.addBlock = function () {
this.block = document.createElement("DIV");
this.block.className = this.classField;
this.block.className += " " + this.obName;
this.placeholder.appendChild(this.block);
};
this.renderTime = function () {
var timeDiff = new Date() - this.startTime + this.startDiff;
this.timeDiff = timeDiff;
timeDiff /= 1000;
// get seconds
this.seconds = Math.round(timeDiff % 60);
// remove seconds from the date
timeDiff = Math.floor(timeDiff / 60);
// get minutes
this.minutes = Math.round(timeDiff % 60);
// remove minutes from the date
timeDiff = Math.floor(timeDiff / 60);
// get hours
this.hours = Math.round(timeDiff % 24);
this.block.innerHTML = this.hours + " h " + this.minutes + " min " + this.seconds + " sec";
// window.setInterval('this.obName.renderTime()',1000);// Uncomment if you want to test your PCs limit
};
this.renderButtons = function () {
var timePassed;
//this.parentTimer = document.getElementsByClassName("timer "+this.obName)[0];
this.startButton = document.createElement("INPUT");
this.startButton.setAttribute("type", "button");
this.startButton.setAttribute("value", "start");
this.startButton.className = "start " + this.obName;
this.stopButton = document.createElement("INPUT");
this.stopButton.setAttribute("type", "button");
this.stopButton.setAttribute("value", "stop");
this.stopButton.className = "stop " + this.obName;
this.placeholder.insertBefore(this.startButton, this.block);
this.placeholder.insertBefore(this.stopButton, this.block);
this.startButton.addEventListener("click", function () {
//if (this.hours === 0 && this.minutes === 0 && this.seconds === 0){
self.startTime = new Date();
// }
tm = window.setInterval(self.renderTime.bind(self), 1000);
});
this.stopButton.addEventListener("click", function () {
window.clearInterval(tm);
self.startDiff = self.timeDiff;
console.log(':', self, self.startDiff);
//timePassed = this.endTime - this.startTime;
//endTime = new Date();
// timePassed = endTime - startTime;
});
//give listener to clear and start interval
};
}
function createNewTimer() {
obName = document.getElementById("ObName").value;
if (obName !== "") {
obName = new TimerObject(obName);
obName.addBlock();
obName.renderButtons();
obName.renderTime();
//window.setInterval('obName.renderTime()',1000);
} else {
document.getElementById("ObName").value = "Fill me";
}
}
There were several issues with the code:
1. Some functions weren't being bound to the correct context (this).
2. The reference set to "obName" was global and constantly changing to the newly created instance.
3. The start time variable was global and constantly being reset every time you called the renderTime function.
I have made the modifications to your code in jsFiddle and they can be found in this update: http://jsfiddle.net/3qxoea52/5/
Rendering:
this.renderTime = function (startTime) {
if( startTime ) {
this.startTime = startTime;
}
this.endTime = new Date();
// time difference in ms
this.timeDiff = this.endTime - this.startTime;
// strip the miliseconds
this.timeDiff /= 1000;
// get seconds
this.seconds = Math.round(this.timeDiff % 60);
// remove seconds from the date
this.timeDiff = Math.floor(this.timeDiff / 60);
// get minutes
this.minutes = Math.round(this.timeDiff % 60);
// remove minutes from the date
this.timeDiff = Math.floor(this.timeDiff / 60);
// get hours
this.hours = Math.round(this.timeDiff % 24);
this.block.innerHTML = this.hours + " h " + this.minutes + " min " + this.seconds + " sec";
// window.setInterval('this.obName.renderTime()',1000);// Uncomment if you want to test your PCs limit
}
Binding:
this.startButton.addEventListener("click", function () {
//if (this.hours === 0 && this.minutes === 0 && this.seconds === 0){
this.startTime = new Date();
// }
this.tm = window.setInterval(this.renderTime.bind(this), 1000);
}.bind(this))
this.stopButton.addEventListener("click", function () {
window.clearInterval(this.tm);
//timePassed = this.endTime - this.startTime;
//endTime = new Date();
// timePassed = endTime - startTime;
}.bind(this))
CreateTimer:
function createNewTimer() {
obName = document.getElementById("ObName").value;
if (obName !== "") {
obName = new timerObject(obName);
obName.addBlock();
obName.renderButtons();
startTime = new Date();
obName.renderTime(startTime);
//window.setInterval('obName.renderTime()',1000);
} else {
document.getElementById("ObName").value = "Fill me";
}
};