i want to open a div after countdown timer stops - javascript

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.

Related

creating a countdown timer in javascript with automatic reload

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>

How to keep running my Countdown after a refresh?

I'm learning JS and I'm stuck...
I want to create a countdown (it's done, my countdown is working) who keep running when the page is reloaded.
I used the sessionStorage to "save" the countdown value and also to check if a sessionStorage exists when the page is loaded.
The problem is, I don't know how keep running the countdown with values saved in the sessionStorage.
Could you please help me?
class Timer {
constructor(secondes, minutes) {
this.secondes = secondes;
this.minutes = minutes;
this.button = document.getElementById("button");
this.counter = document.getElementById("counter");
this.storageCheck();
}
countdown(minutes) {
var seconds = this.secondes;
var mins = this.minutes;
var myCounter = this.counter;
function tick() {
var current_minutes = mins-1;
seconds--;
myCounter.innerHTML = current_minutes + ":" + (seconds < 10 ? "0" : "") + seconds;
var duration = sessionStorage.setItem("timer", myCounter.innerHTML);
if( seconds > 0 ) {
setTimeout(tick, 1000);
} else {
if(mins > 1){
countdown(mins-1);
}
}
}
tick();
}
buttonClick() {
button.addEventListener("click", () => {
this.countdown(this.minutes);
})
}
storageCheck() {
if (sessionStorage.getItem("timer")) {
// keep the countdown running
}
}
}
let newTimer = new Timer(60, 20);
newTimer.buttonClick();
<!DOCTYPE html>
<html>
<head>
<title>Test Countdown</title>
</head>
<body>
<div id="counter"></div>
<button id="button">Run</button>
<script type="text/javascript" src="countdown.js"></script>
</body>
</html>
In constructor before initializing secondes and minutes check if they are in the storage.If they dont exists then only set the this.secondes = secondes and this.minutes = minutes;
constructor(secondes, minutes) {
this.button = document.getElementById("button");
this.counter = document.getElementById("counter");
if(!this.storageCheck()){ //check if seconds are mins are stored in storage
this.secondes = secondes; //if not set mins and sec to value passed in constructor
this.minutes = minutes;
}
else{
this.countdown(this.minutes);
}
}
In storage check function , check if the values are there, if there get the values and set to this.secondes and this.minutes and return true else return false
storageCheck() {
//if both mins and secs exists
if (sessionStorage.getItem("mins") &&sessionStorage.getItem("secs")) {
// keep the countdown running
this.minutes=parseInt(sessionStorage.getItem("mins"));//get min
this.secondes=parseInt(sessionStorage.getItem("secs"));//get secs
return true;
}
else
return false;
}
and in countdown funciton save the values to storage
sessionStorage.setItem("mins",vm.minutes);//set current min
sessionStorage.setItem("secs",vm.secondes);//set current sec
Try running this here :https://jsbin.com/bavexigute/1/edit?html,js,console,output
class Timer {
constructor(secondes, minutes) {
this.button = document.getElementById("button");
this.counter = document.getElementById("counter");
if(!this.storageCheck()){ //check if seconds are mins are stored in storage
this.secondes = secondes; //if not set mins and sec to value passed in constructor
this.minutes = minutes;
}
else{
this.countdown();
}
}
countdown() {
debugger;
var vm=this;
if(!(this.minutes-1<0))
this.minutes--;
let tick= function(){
vm.secondes--
if(vm.secondes==0){
vm.secondes=59;
vm.minutes--;
}
vm.counter.innerHTML = vm.minutes + ":" + (vm.secondes < 10 ? "0" : "") + vm.secondes;
if(vm.minutes == 0 && vm.secondes-1==0){
vm.secondes--;
vm.counter.innerHTML = vm.minutes + ":" + vm.secondes-1;
}
else{
setTimeout(tick,1000);
}
sessionStorage.setItem("mins",vm.minutes);//set current min
sessionStorage.setItem("secs", vm.secondes);//set current sec
}
setTimeout(tick,1000);
}
buttonClick() {
button.addEventListener("click", () => {
this.countdown();
})
}
storageCheck() {
//if both mins and secs exists
if (sessionStorage.getItem("mins") && sessionStorage.getItem("secs")) {
// keep the countdown running
this.minutes=parseInt(sessionStorage.getItem("mins"));//get min
this.secondes=parseInt(sessionStorage.getItem("secs"));//get secs
return true;
}
else
return false;
}
}
let newTimer = new Timer(60, 20);
newTimer.buttonClick();
You could use your storage check function to override the minutes and seconds arguments if it exists.
constructor(mins, secs) {
this.mins = mins
this.secs = secs
this.checkStorage = this.checkStorage.bind(this)
this.checkStorage(mins, secs)
}
checkStorage(mins, secs) {
if(window.storage) { // or whatever
this.secs = window.storage.secs
this.mins = window.storage.mins
}
}
Something along those lines. Basically just have the setStorage function change the values that have been set in the constructor.
You can do a simple trick by doing this
window.onload = function() {
let minutes = sessionStorage.getItem("minutes")
let seconds = sessionStorage.getItem("seconds")
let newTimer = new Timer(seconds, minutes);
};
And in sessionStorage instead of storing the whole innerHtml store minutes and seconds hopefully it will solve your problem

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>

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

JavaScript Timer: Code Working Uncaught TypeError

I am using a javascript timer on a page, which redirects the user after a finite time. The code is doing exactly what I want it to but it continues to throw errors in the console. The error message I get is
Uncaught TypeError: Cannot set property 'textContent' of null
//Countdown Timer
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(".cdtimer"),
s6timer = new CountDownTimer(20);
s6timer.onTick(format).onTick(redirect).start();
function redirect() {
if (s6timer.expired()) {
window.location.replace("../assessmentportal/sectiontimeout.php");
}
};
function format(minutes, seconds) {
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ':' + seconds;
};
};
});
This happens because this call document.querySelector(".cdtimer") returns null. There are 2 possible reasons:
There are no element with class name cdtimer
You are running your script before DOM loaded
Is your assignment of display actually returning a DOM element? If it can't find anything (typo, perhaps?) it will return null.

Categories

Resources