JS- Countdown Timer Alerts - javascript

Need some help with my code, I can't get my alerts to work with my countdown timer. They should be alerting at 4,3,2 minutes left on the timer. I currently can't get the alerts to fire at all, sometimes they would fire but each second after 4, the alert for "4" would fire. I need it to just go once... Any help would be appreciated
Heres my script
var running=false
var endTime=null
var timerID=null
function startTimer(){
running=true
now=new Date()
now=now.getTime()
endTime=now+(1000*60*5)
showCountDown()
}
function showCountDown(){
var now=new Date()
now=now.getTime()
if (endTime-now<=239990 && endTime-now>240010){alert("4")};
if (endTime-now<=179990 && endTime-now>180010){alert("3")};
if (endTime-now<=119990 && endTime-now>120010){alert("2")};
if (endTime-now<=0){
stopTimer()
alert("Time is up. Put down pencils")
} else {
var delta=new Date(endTime-now)
var theMin=delta.getMinutes()
var theSec=delta.getSeconds()
var theTime=theMin
theTime+=((theSec<10)?":0" : ":")+theSec
document.forms[0].timerDisplay.value=theTime
if (running){
timeID=setTimeout("showCountDown()",1000)
}
}
}
function stopTimer(){
clearTimeout(timeID)
running=false
document.forms[0].timerDisplay.value="0.00"
}
Update, Sorry meant minutes instead of seconds
Update 2: Change the ifs, now they fire but keep firing after the 4 second mark
if (endTime-now<=240010 && endTime-now<=239990){alert("4")};
if (endTime-now<=180010 && endTime-now<=179990){alert("3")};
if (endTime-now<=120010 && endTime-now<=119990){alert("2")};

Why are you calling clearTimeout? setTimeout invokes its callback only once. There is no need to clear it. Also you could just have a variable that stores the minutes until the end of the countdown and decrement that by one in each iteration.
The simplest solution might look like this
function startTimer(minutesToEnd) {
if(minutesToEnd > 0) {
if(minutesToEnd <= 4) {
console.log(minutesToEnd);
}
setTimeout(startTimer, 60000, minutesToEnd - 1);
} else {
console.log("Time is up. Put down pencils")
}
}

I actually spent some time working on this. I have no idea if this is what you wanted, but I created a timer library. I have a working demo for you. I had fun making this. Let me know what you think:
JS:
(function () {
var t = function (o) {
if (!(this instanceof t)) {
return new t(o);
}
this.target = o.target || null;
this.message = o.message;
this.endMessage = o.endMessage;
//setInterval id
this.si = -1;
//Initial start and end
this.startTime = null;
this.endTime = null;
this.interTime = null;
this.duration = o.duration || 1000 * 60 * 5;
//looping speed miliseconds it is best to put the loop at a faster speed so it doesn't miss out on something
this.loop = o.loop || 300;
//showing results miliseconds
this.show = o.show || 1000;
};
t.fn = t.prototype = {
init: function () {}
};
//exporting
window.t = t;
})();
//Timer Functions ---
t.fn.start = function () {
this.startTime = new Date();
this.interTime = this.startTime.getTime();
this.endTime = new Date().setMilliseconds(this.startTime.getMilliseconds() + this.duration);
//returns undefined... for some reason.
console.log(this.endTime);
var $this = this;
this.writeMessage(this.duration);
this.si = setInterval(function () {
var current = new Date(),
milli = current.getTime();
if (milli - $this.interTime >= $this.show) {
var left = $this.endTime- milli;
if (left <= 0) {
$this.stop();
} else {
$this.interTime = milli;
$this.writeMessage(left);
}
}
}, this.loop);
return this;
};
t.fn.writeMessage = function(left){
this.target.innerHTML = this.message + ' ' + Math.floor(left / 1000);
return this;
};
t.fn.stop = function () {
//stopping the timer
clearInterval(this.si);
this.target.innerHTML = this.endMessage;
return this;
};
//Not chainable
t.fn.isRunning = function () {
return this.timer > -1;
};
var timer = t({
target: document.getElementById('results'),
loop: 50,
duration: 10000,
show: 1000, //default is at 1000 miliseconds
message: 'Time left: ', //If this is ommited then only the time left will be shown
endMessage: 'Time is up. Put down your pencils'
}).start();
document.getElementById('stop').onclick = function(){
timer.stop();
};
HTML:
<div id="results"></div>
<button id="stop">Stop</button>
Demo here
Update: I added some stuff
Demo 2
Update 2: I fixed the bug where 10 would hop straight to 8
Demo 3

Related

Javascript Countdown Timer goes too fast even with boolean switch

I have the following countdown function in javascript:
countdownTimer() {
// exit method if it is active
if(this.isCountdownActive == true){
return;
}
// first time set true
this.isCountdownActive = true
this.countdown = 10
// Define the work to be done
var doWork = () => {
if(this.countdown <= 0) {
ticker.stop();
this.countdown = 10
this.isCountdownActive = false
if (this.thisUser.captain) {
Store.submitTurnEnd();
}
}
this.countdown -= 1;
};
// Define what to do if something goes wrong
var doError = function() {
console.warn('The drift exceeded the interval.');
};
// (The third argument is optional)
var ticker = new Util.AdjustingInterval(doWork, 1000, doError);
ticker.start()
},
Here is the adjusting interval function
function AdjustingInterval(workFunc, interval, errorFunc) {
var that = this;
var expected, timeout;
this.interval = interval;
this.start = function() {
expected = Date.now() + this.interval;
timeout = setTimeout(step, this.interval);
}
this.stop = function() {
clearTimeout(timeout);
}
function step() {
var drift = Date.now() - expected;
if (drift > that.interval) {
// You could have some default stuff here too...
if (errorFunc) errorFunc();
}
workFunc();
expected += that.interval;
timeout = setTimeout(step, Math.max(0, that.interval-drift));
}
}
I believe this should work, however the timer still runs too fast occasionally and doesn't reset correctly. I would say 75% of the time it works fine, but after I click it gets "jumpy" and goes too fast. Also, the timer doesn't stop correctly. So that it cycles continuously.
Thanks for the help.
Just adjust the ms to however precise you want
const span = document.getElementById("t");
let d = new Date();
d.setHours(d.getHours()+1); // demo time
let tId = setInterval(() => span.innerText = new Date(d.getTime()-new Date().getTime()).toLocaleTimeString(),100)
<span id="t"></span>

Closure in timer countdown javascript

I'm using the countdown timer from here: The simplest possible JavaScript countdown timer?
I'm adding the reset, pause and resume functionalities to the code.
//=================== Timer class ==============================
function CountDownTimer(duration, granularity) {
this.duration = duration
this.granularity = granularity || 1000;
this.tickFtns = [];
this.running = false;
this.resetFlag = false;
}
CountDownTimer.prototype.start = function() {
console.log('calling start');
if (this.running) {
return;
}
this.running = true;
var start = Date.now(),
that = this,
diff, obj,
timeoutID;
(function timer() {
diff = that.duration - (((Date.now() - start) / 1000) | 0);
if (that.resetFlag) {
console.log('Reset inside closure');
clearTimeout(timeoutID);
diff = 0;
that.resetFlag = false;
that.running = false;
return;
}
console.log(diff);
if (diff > 0) {
timeoutID = 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.prototype.setTime = function(secs) {
this.duration = secs;
}
CountDownTimer.prototype.reset = function() {
this.resetFlag = true;
}
CountDownTimer.parse = function(seconds) {
return {
'minutes': (seconds / 60) | 0,
'seconds': (seconds % 60) | 0
};
};
window.onload = function () {
timer = new CountDownTimer(25);
timer.start();
$('#button').click(function() {
console.log("before reset");
console.log(timer);
console.log("after reset");
timer.reset();
console.log(timer);
// timer.setTime(10);
timer.start();
})
}
HTML for testing, check the output at console.
<script src="main.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<button id='button'> </button>
1) Is function timer() in start a closure?
2) I added a resetFlag, the reset method, and the check for resetFlag in the start function. I'm able to stop the timer immediately, but can't start it after that. How do I fix the error?
25
24
23
main.js:64 Reset inside closure
(it supposed to countdown from 25 to 0, and when I press #button, the timer reset and should count from 10 to 0.
================================EDITS==========================================:
After adding running = false, it's still not working.
before reset
main.js:128 CountDownTimer {duration: 25, granularity: 1000, tickFtns: Array[0], running: true, resetFlag: false}
main.js:129 after reset
main.js:131 CountDownTimer {duration: 25, granularity: 1000, tickFtns: Array[0], running: true, resetFlag: true}
calling start
main.js:64 Reset inside closure
It seems that there's some lag after resetting the timer? (The reset inside closure suppposed to appear before the after reset.

Javascript Countdown Timer redirect after End

I have a JavaScript Countdown and I want it to redirect to another site when the countdown ends.
How can I do that?
Code:
(function ( $ ) {
"use strict";
$.fn.countdownTimer = function( options ) {
// This is the easiest way to have default options.
var settings = $.extend({
endTime: new Date()
}, options );
var $this = $(this);
var $seconds = $this.find(".time.seconds");
var $minutes = $this.find(".time.minutes");
var $hours = $this.find(".time.hours");
var $days = $this.find(".time.days");
var seconds = 0;
var minutes = 0;
var days = 0;
var hours = 0;
var switchCountdownValue = function ($obj, val) {
// Add leading zero
var s = val+"";
while (s.length < 2) s = "0" + s;
if(Modernizr.cssanimations) {
// Fade out previous
var prev = $obj.find(".value").addClass("fadeOutDown").addClass("animated");
// Add next value
var next = $("<div class='value'>" + s + "</div>");
$obj.prepend(next);
// Fade in next value
next.addClass("fadeInDown").addClass("animated");
// Remove from DOM on animation end
// Fix for Safari (if window is not active, then webkitAnimationEnd doesn't fire, so delete it on timeout)
var to = setTimeout(function(){ prev.remove() }, 200);
prev.one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
prev.remove();
clearTimeout(to);
});
} else {
// Remove previous value
var prev = $obj.find(".value").remove();
// Add next value
var next = $("<div class='value'>" + s + "</div>");
$obj.prepend(next);
}
}
var timerId = countdown(settings.endTime,
function(ts) {
if(seconds != ts.seconds) {
switchCountdownValue($seconds, ts.seconds);
seconds = ts.seconds;
}
if(minutes != ts.minutes) {
switchCountdownValue($minutes, ts.minutes);
minutes = ts.minutes;
}
if(hours != ts.hours) {
switchCountdownValue($hours, ts.hours);
hours = ts.hours;
}
if(days != ts.days) {
switchCountdownValue($days, ts.days);
days = ts.days;
}
},
countdown.DAYS|countdown.HOURS|countdown.MINUTES|countdown.SECONDS);
return this;
};}( jQuery ));
HTML:
<script type="text/javascript">
$().ready(function(){
$(".countdown").countdownTimer({
endTime: new Date("May 13, 2016 20:00:00")
});
$("#notifyMe").notifyMe();
$("#bg-canvas").bezierCanvas({
maxStyles: 1,
maxLines: 50,
lineSpacing: .07,
spacingVariation: .07,
colorBase: {r: 120,g: 100,b: 220},
colorVariation: {r: 50, g: 50, b: 30},
moveCenterX: 0,
moveCenterY: 0,
delayVariation: 3,
globalAlpha: 0.4,
globalSpeed:30,
});
$().ready(function(){
$(".overlap .more").click(function(e){
e.preventDefault();
$("body,html").animate({scrollTop: $(window).height()});
});
});
});
</script>
C&P Code from internet:
http://pastebin.com/CvYNBSED
The Countdown is working perfectly, but I want a redirect when the Countdown ends.
Edit:
Thanks for helping but my problem is, how can I make the if question or how can I check when the countdown has finished?
I know how to make a redirect but I dont know how to check if the countdown is finished.
How to redirect to another webpage in JavaScript/jQuery?
// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");
// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";
as long as your countdown is working, as you said.
Edit.
try the check here:
var timerId = countdown(settings.endTime,
function(ts) {
if(seconds != ts.seconds) {
switchCountdownValue($seconds, ts.seconds);
seconds = ts.seconds;
}
if(minutes != ts.minutes) {
switchCountdownValue($minutes, ts.minutes);
minutes = ts.minutes;
}
if(hours != ts.hours) {
switchCountdownValue($hours, ts.hours);
hours = ts.hours;
}
if(days != ts.days) {
switchCountdownValue($days, ts.days);
days = ts.days;
}
// maybe this will work.
// I didn't check your countdown library because it's minified / uglified
if(days == 0 && hours == 0 && minutes == 0 && seconds == 0){
//redirect here
}
},
countdown.DAYS|countdown.HOURS|countdown.MINUTES|countdown.SECONDS);
How about extending your countdownTimer class to add a onDone function to be executed upon completion of the countdown?
...
var settings = $.extend({
endTime: new Date(),
onDone: function () {
window.location.href('http://www.google.com')
}
}, options );
...
Then have your component execute that method when the countdown finishes:
...
prev.one('webkitAnimationEnd ...', function(){
if (settings.onDone) {
settings.onDone();
}
});
...
Just a thought, but to simply answer the question of redirect, then #nonsensei's should suffice.

Countdown and bootstrap progress bar "bump"

I'm working on a little "web app" for a quiz.
Each slide has got a certain amount of time to be answered (or 0 to infinite time).
I find JS here to do the countdown:
function Countdown(options) {
var timer,
instance = this,
seconds = options.seconds || 10,
updateStatus = options.onUpdateStatus || function () {},
counterEnd = options.onCounterEnd || function () {};
function decrementCounter() {
updateStatus(seconds);
if (seconds === 0) {
counterEnd();
instance.stop();
}
seconds--;
}
this.start = function () {
clearInterval(timer);
timer = 0;
seconds = options.seconds;
timer = setInterval(decrementCounter, 1000);
};
this.stop = function () {
clearInterval(timer);
};
}
var myCounter = new Countdown({
seconds: timetogo, // number of seconds to count down
onUpdateStatus: function (sec) {
elapsed = timetogo - sec;
$('.progress-bar').width(((elapsed / timetogo) * 100) + "%");
}, // callback for each second
onCounterEnd: function () {
//alert('counter ended!');
} // final action
});
myCounter.start();
I made a jsfiddle here :
https://jsfiddle.net/mitchum/kz2400cc/2/
But i am having trouble when you go to the next slide, the progress bar "bump".
after looking into "live source panel from chrome" I saw it's like the first "counter" is not stopped and still runs.
Do you have any tips or hint to help me to solve my bug ?
Thanks
You must pay attention to the scope of the variables. I change the "var myCounter" under document ready in "var myCounterFirst". Check the updated JSFiddle.
var timetogoFirst = $('.current').attr("data-time");
var myCounterFirst = new Countdown({
seconds: timetogoFirst, // number of seconds to count down
onUpdateStatus: function (sec) {
elapsed = timetogoFirst - sec;
$('.progress-bar').width(((elapsed / timetogoFirst) * 100) + "%");
}, // callback for each second
onCounterEnd: function () {
alert('counter ended!');
} // final action
});
myCounterFirst.start();

Javascript scope error issue

I wrote this code that starts a timer. I fire a function that restarts the timer when it reaches 0. It works, but I get an error in the console that says Uncaught TypeError: Cannot read property 'restartTimer' of undefined. It has to do with this.restartTimer();
timer = utility.math.surveyTimer({
seconds: time,
onUpdateStatus: function(remainingTime) {
$(surveyTimerNode).text(remainingTime);
},
restartTimer: function() {
window.TimerInterval = timer.start();
},
onCounterEnd: function() {
if (utility.bool.isQuestionScreen()) {
if (utility.bool.surveyWillLoop()) {
data.setPersistentSurveyData('DSM_SURVEY_SCREENS', surveyScreens);
data.setPersistentSurveyData('DSM_SURVEY_SCREEN_ORDER', surveyScreenOrder);
tagData = data.getPersistentSurveyData('DSM_SURVEY_DATA');
apiParam = api.helper.buildAPIParam('surveyTimeout', tagData);
api.post.postToAPI(apiParam);
parent.resetSurveyProgress();
parent.moveToNextScreen();
this.restartTimer();
} else {
parent.goToEndscreen();
}
}
}
});
window.TimerInterval = timer.start();
No errors in JSLint, just errors on run. What's so bizarre is that it works, the timer does reset. How do I remove this error?
Here's the function that actually does the timer counting:
this.surveyTimer = function (options) {
var timer,
instance = this,
minutes,
secondsMinusMinutes,
remainingTime,
seconds = options.seconds || 30,
updateStatus = options.onUpdateStatus || function () {
return undefined;
},
counterEnd = options.onCounterEnd || function () {
return undefined;
};
function zeroPad(n) {
return (n < 10) ? ("0" + n) : n;
}
function decrementCounter() {
minutes = Math.floor(seconds / 60);
secondsMinusMinutes = seconds - minutes * 60;
remainingTime = minutes + ':' + zeroPad(secondsMinusMinutes);
updateStatus(remainingTime);
if (seconds === 0) {
counterEnd();
instance.stop();
}
seconds -= 1;
}
this.start = function () {
clearInterval(timer);
timer = 0;
seconds = options.seconds;
timer = setInterval(decrementCounter, 1000);
return timer;
};
this.stop = function () {
clearInterval(timer);
};
return this;
};
Just a guess, but I think your use of this in your options object is not the this you think it is...
Try changing your implementation of surveyTimer, where it is currently:
counterEnd();
to:
counterEnd.call(options);

Categories