Using a javascript timer, I have a Timer that starts at 00:00, and should stop at 00:10 (runs for 10 seconds).
The problem is, how can I continuously check the current value of the timer to stop it after 10 seconds?
<script>
window.onload = function() {
var timer = new Tock({
callback: function () {
$('#clockface').val(timer.msToTime(timer.lap()));
}
});
timer.start("00:01.780");
}
</script>
<h2>Timer</h2>
<input id="clockface" placeholder="00:00:00">
Current Attempts:
setTimeout(timer,1000);
$('#clockface').change(function(){
if($('#clockface').val() == "00:05.000") {
timer.stop();
alert("True");
} else {
alert("False");
}
})
This seems to work (JSFiddle: http://jsfiddle.net/gabrieldeliu/jLg2wvvL/1/):
var start_time;
var timer = new Tock({
callback: function() {
if (start_time && timer.lap() - start_time > 5000) {
console.log('Stopped at ' + timer.msToTime(timer.lap()));
timer.stop();
}
}
});
timer.start("00:01.780");
start_time = timer.lap();
console.log('Starts at ' + timer.msToTime(start_time));
Try like this:
var init = new Date().getTime();
var inter = setInterval(function(){
if(new Date().getTime() - init > 1000)
{
clearInterval(inter);
return;
}
}, 2500);
Related
I'm trying to build a countdown with js and when the countdown is done an element which is hidden during the countdown needs to be visible.
I've got so far but can't seem to figure out why the element .homepage_search doesn't become visible.
function timer(time,update,complete) {
var start = new Date().getTime();
var interval = setInterval(function() {
var now = time-(new Date().getTime()-start);
if( now <= 0) {
clearInterval(interval);
complete();
}
else update(Math.floor(now/1000));
},100);
}
timer(
6000,
function(timeleft) {
document.getElementById('timer').innerHTML = timeleft;
},
function() { // what to do after
$('.homepage_search').css({"visibility":"visible"});
}
);
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.
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();
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
I got this function that starts a timer on this format 00:00:00 whenever I click on a button. But I don't know how to do functions resume and pause. I've found some snippets that I thought could be helpful but I couldn't make those work. I'm new to using objects in js.
function clock() {
var pauseObj = new Object();
var totalSeconds = 0;
var delay = setInterval(setTime, 1000);
function setTime() {
var ctr;
$(".icon-play").each(function () {
if ($(this).parent().hasClass('hide')) ctr = ($(this).attr('id')).split('_');
});
++totalSeconds;
$("#hour_" + ctr[1]).text(pad(Math.floor(totalSeconds / 3600)));
$("#min_" + ctr[1]).text(pad(Math.floor((totalSeconds / 60) % 60)));
$("#sec_" + ctr[1]).text(pad(parseInt(totalSeconds % 60)));
}
}
pad() just adds leading zeros
I think it will be better if you will create clock object. See code (see Demo: http://jsfiddle.net/f9X6J/):
var Clock = {
totalSeconds: 0,
start: function () {
var self = this;
this.interval = setInterval(function () {
self.totalSeconds += 1;
$("#hour").text(Math.floor(self.totalSeconds / 3600));
$("#min").text(Math.floor(self.totalSeconds / 60 % 60));
$("#sec").text(parseInt(self.totalSeconds % 60));
}, 1000);
},
pause: function () {
clearInterval(this.interval);
delete this.interval;
},
resume: function () {
if (!this.interval) this.start();
}
};
Clock.start();
$('#pauseButton').click(function () { Clock.pause(); });
$('#resumeButton').click(function () { Clock.resume(); });
Just clearing the interval wouldn't work, because totalSeconds would not get incremented.
I would set up a flag that determines if the clock is paused or not.
This flag would be simply set upon calling pause() or unset upon resume().
I separated the totalSeconds increase to a 'tick' timeout that will always be running, even when paused (so that we can keep track of the time when we resume).
The tick function will therefore only update the time if the clock is not paused.
function clock()
{
var pauseObj = new Object();
var totalSeconds = 0;
var isPaused = false;
var delay = setInterval(tick, 1000);
function pause()
{
isPaused = true;
}
function resume()
{
isPaused = false;
}
function setTime()
{
var ctr;
$(".icon-play").each(function(){
if( $(this).parent().hasClass('hide') )
ctr = ($(this).attr('id')).split('_');
});
$("#hour_" + ctr[1]).text(pad(Math.floor(totalSeconds/3600)));
$("#min_" + ctr[1]).text(pad( Math.floor((totalSeconds/60)%60)));
$("#sec_" + ctr[1]).text(pad(parseInt(totalSeconds%60)));
}
function tick()
{
++totalSeconds;
if (!isPaused)
setTime();
}
}
Use window.clearInterval to cancel repeated action which was set up using setInterval().
clearInterval(delay);
<html>
<head><title>Timer</title>
<script>
//Evaluate the expression at the specified interval using setInterval()
var a = setInterval(function(){disp()},1000);
//Write the display() for timer
function disp()
{
var x = new Date();
//locale is used to return the Date object as string
x= x.toLocaleTimeString();
//Get the element by ID in disp()
document.getElementById("x").innerHTML=x;
}
function stop()
{
//clearInterval() is used to pause the timer
clearInterval(a);
}
function start()
{
//setInterval() is used to resume the timer
a=setInterval(function(){disp()},1000);
}
</script>
</head>
<body>
<p id = "x"></p>
<button onclick = "stop()"> Pause </button>
<button onclick = "start()"> Resume </button>
</body>
</html>