creating a countdown timer in javascript with automatic reload - javascript

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>

Related

Add minutes to dom countdown timer

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;
}
}

How to pause and resume timer in JavaScript?

I've been trying to create my own "pomodoro" like timer and got stuck when trying to pause and pause and resume the timer. I want my timer to start at 40:00, it currently runs when the "Start" button is pressed and stops when I press a "Stop" button, but it doesn't resume when I press the "Start" button again.
var startButton = document.getElementById("startButton");
var stopButton = document.getElementById("stopButton");
var resetButton = document.getElementById("resetButton");
var isRunning = false;
startButton.addEventListener("click", function () {
trigger();
});
stopButton.addEventListener("click", function () {
stopTimer();
});
resetButton.addEventListener("click", function() {
resetTimer();
});
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
if (isRunning === false) {
isRunning = 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;
timer--;
}, 1000);
} else {
isRunning = !isRunning;
}
if (timer < 0) {
clearInterval(isRunning);
}
};
function trigger() {
var fiveMinutes = 2400,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
function stopTimer() {
clearInterval(isRunning);
};
<div class="main-downwards-buttons">
<button id="startButton" type="button" class="btn-success">Start</button>
<button id="stopButton" type="button" class="btn-danger">Stop</button>
<button id="resetButton" type="button" class="btn-secondary">Reset</button>
</div>
Declare fiveMinutes in the global scope and reset it only when reset button is clicked.
And you need to update its value inside the anonymous function to keep it running. The issue here is that you can have only one counter.
var startButton = document.getElementById("startButton");
var stopButton = document.getElementById("stopButton");
var resetButton = document.getElementById("resetButton");
var isRunning = false;
var fiveMinutes = 2400;
var display = document.querySelector('#time');
startButton.addEventListener("click", function () {
startTimer(fiveMinutes, display);
});
stopButton.addEventListener("click", function () {
stopTimer();
});
resetButton.addEventListener("click", function() {
stopTimer();
fiveMinutes = 2400;
display.textContent = '0:00';
});
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
if (isRunning === false) {
isRunning = 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;
timer --;
// You need to update the original variable
fiveMinutes --;
}, 1000);
} else {
isRunning = !isRunning;
}
if (timer < 0) {
stopTimer();
}
};
function stopTimer() {
clearInterval(isRunning);
isRunning = false;
};
<div id="time">0:00</div>
<div class="main-downwards-buttons">
<button id="startButton" type="button" class="btn-success">Start</button>
<button id="stopButton" type="button" class="btn-danger">Stop</button>
<button id="resetButton" type="button" class="btn-secondary">Reset</button>
</div>

Prevent timer reset on page refresh

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 want to open a div after countdown timer stops

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.

Countdown Timer is not showing in javascript

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);

Categories

Resources