Pause and Resume the counting values from localstorage - javascript

I am using this code for countdown timer to a quiz test. Its working Fine. In this I need to add two buttons one is Pause button and another one is Resume button. When I click a Pause button it's stop time and when I click a Resume button it's start from where I pause the time.
I have tried this code. It's not working.
HTML Code
<div class="div__time">
<div style="display: none;" id="overall_time"></div>
<div id="overall_times"></div>
<div class="total_time"></div>
</div>
<input id="pauseButton" type="button" value="Pause">
<input id="resumeButton" type="button" value="Resume">
JS Code
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js" type="text/javascript"></script>
<script>
var speaking_ms = "00:00:10";
var speaking_ms_arr = speaking_ms.split(":");
var speaking_time_min_sec = (+speaking_ms_arr[0]) * 60 * 60 + (+speaking_ms_arr[1]) * 60 + (+speaking_ms_arr[2]);
var speaking_time_min_sec = parseInt(speaking_time_min_sec) + 1;
var speaking_value;
if (localStorage.getItem("speaking_counter")) {
if (localStorage.getItem("speaking_counter") <= 0) {
speaking_value = speaking_time_min_sec;
} else {
speaking_value = localStorage.getItem("speaking_counter");
}
} else {
speaking_value = speaking_time_min_sec;
}
document.getElementById('overall_time').innerHTML = speaking_value;
var speaking_counter = function() {
if (speaking_value <= 0) {
localStorage.setItem("speaking_counter", speaking_time_min_sec);
} else {
speaking_value = parseInt(speaking_value) - 1;
localStorage.setItem("speaking_counter", speaking_value);
}
document.getElementById('overall_time').innerHTML = speaking_value;
if (speaking_value == 0) {
localStorage.setItem("speaking_counter", speaking_value);
setTimeout(function() {
clearInterval(interval);
}, 1000);
}
var hours = Math.floor(speaking_value / 3600);
var minutes = Math.floor(speaking_value % 3600 / 60);
var seconds = Math.floor(speaking_value % 3600 % 60);
var red_time = hours + ' : ' + minutes + ' : ' + seconds;
document.getElementById('overall_times').innerHTML = red_time;
};
var interval = setInterval(function() {
speaking_counter();
}, 1000);
var Clock = {
pause: function() {
clearInterval(this.interval);
delete this.interval;
},
resume: function() {
if (!this.interval) this.start();
}
};
$('#pauseButton').click(function() { Clock.pause(); });
$('#resumeButton').click(function() { Clock.resume(); });
</script>
Fiddle Link
Thanks in Advance.

I changed the end of the code in the fiddle and it worked: https://jsfiddle.net/bohv0j9w/5/
var Clock = {
pause: function() {
clearInterval(interval);
interval = null;
},
resume: function() {
if (!interval) interval = setInterval(speaking_counter, 1000);
}
};
document.querySelector('#pauseButton').addEventListener("click", Clock.pause);
document.querySelector('#resumeButton').addEventListener("click", Clock.resume);
In your version this.internal is undefined you may want to learn about "this" and scopes in js. And $(...) is a syntax that requires the lib jquery (not included in the fiddle), the vanilla js equivalent is "document.querySelector", you should read the MDN article about this function.
Finally, your syntax is a bit old school. If you use localStorage you aren't targeting very old browsers maybe you should avoid jquery and use keywords such as "const".

Following are your mistakes. (Fiddle link)
var Clock = {
pause: function() {
clearInterval(this.interval);//(this.interval is undefined, replace it with interval)
^^^^
delete this.interval;//(this.interval is undefined, replace it with interval)
^^^^
},
resume: function() {
if (!this.interval) this.start();//(this.interval is undefined, replace it typeof interval === undefined to check whether interval exists or not)
^^^^
^^^^^^^^^^^ //(this.start() is also not defined, replace it with start() and move `var interval = setInterval(fun.....` into new start function)
}
};
look at following code.
var speaking_ms = "00:00:10";
var speaking_ms_arr = speaking_ms.split(":");
var speaking_time_min_sec = (+speaking_ms_arr[0]) * 60 * 60 + (+speaking_ms_arr[1]) * 60 + (+speaking_ms_arr[2]);
var speaking_time_min_sec = parseInt(speaking_time_min_sec) + 1;
var speaking_value;
if (localStorage.getItem("speaking_counter")) {
if (localStorage.getItem("speaking_counter") <= 0) {
speaking_value = speaking_time_min_sec;
} else {
speaking_value = localStorage.getItem("speaking_counter");
}
} else {
speaking_value = speaking_time_min_sec;
}
document.getElementById('overall_time').innerHTML = speaking_value;
var speaking_counter = function() {
if (speaking_value <= 0) {
localStorage.setItem("speaking_counter", speaking_time_min_sec);
} else {
speaking_value = parseInt(speaking_value) - 1;
localStorage.setItem("speaking_counter", speaking_value);
}
document.getElementById('overall_time').innerHTML = speaking_value;
if (speaking_value == 0) {
localStorage.setItem("speaking_counter", speaking_value);
setTimeout(function() {
clearInterval(interval);
}, 1000);
}
var hours = Math.floor(speaking_value / 3600);
var minutes = Math.floor(speaking_value % 3600 / 60);
var seconds = Math.floor(speaking_value % 3600 % 60);
var red_time = hours + ' : ' + minutes + ' : ' + seconds;
document.getElementById('overall_times').innerHTML = red_time;
};
var start = function() {
interval = setInterval(function() {
speaking_counter();
}, 1000);
}
var Clock = {
pause: function() {
clearInterval(interval);
delete interval;
},
resume: function() {
if (typeof interval === 'undefined') start();
}
};
$('#pauseButton').click(function() { Clock.pause(); });
$('#resumeButton').click(function() { Clock.resume(); });
start();

I have fixed your solution and implemented what you were trying to implement. There were minor issues with your solution which i fixed.
1. You were using this to access interval variable that was not part of the clock object in which you were accessing the variable.
2. You were using this.start() function in the resume function of clock object which was not part of the clock object.
3. JQuery used to define events was not included in the fiddle. Although it is included in the code pasted in the question.
html:
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
</head>
<body>
<div class="div__time">
<div style="display: none;" id="overall_time"></div>
<div id="overall_times"></div>
<div class="total_time"></div>
</div>
<input id="pauseButton" type="button" value="Pause">
<input id="resumeButton" type="button" value="Resume">
</body>
js:
var speaking_ms = "00:00:10";
var speaking_ms_arr = speaking_ms.split(":");
var speaking_time_min_sec = (+speaking_ms_arr[0]) * 60 * 60 + (+speaking_ms_arr[1]) * 60 + (+speaking_ms_arr[2]);
var speaking_time_min_sec = parseInt(speaking_time_min_sec) + 1;
var speaking_value;
if (localStorage.getItem("speaking_counter")) {
if (localStorage.getItem("speaking_counter") <= 0) {
speaking_value = speaking_time_min_sec;
} else {
speaking_value = localStorage.getItem("speaking_counter");
}
} else {
speaking_value = speaking_time_min_sec;
}
document.getElementById('overall_time').innerHTML = speaking_value;
var speaking_counter = function() {
if (speaking_value <= 0) {
localStorage.setItem("speaking_counter", speaking_time_min_sec);
} else {
speaking_value = parseInt(speaking_value) - 1;
localStorage.setItem("speaking_counter", speaking_value);
}
document.getElementById('overall_time').innerHTML = speaking_value;
if (speaking_value == 0) {
localStorage.setItem("speaking_counter", speaking_value);
setTimeout(function() {
clearInterval(interval);
}, 1000);
}
var hours = Math.floor(speaking_value / 3600);
var minutes = Math.floor(speaking_value % 3600 / 60);
var seconds = Math.floor(speaking_value % 3600 % 60);
var red_time = hours + ' : ' + minutes + ' : ' + seconds;
document.getElementById('overall_times').innerHTML = red_time;
};
var interval = setInterval(function() {
speaking_counter();
}, 1000);
var Clock = {
pause: function() {
clearInterval(interval);
delete interval;
},
resume: function() {
interval = setInterval(function() {
speaking_counter();
}, 1000);
}
};
$('#pauseButton').click(function() { Clock.pause(); });
$('#resumeButton').click(function() { Clock.resume(); });
Here is the fiddle link: JS Fiddle

You have gotten quite a few answers so far, I wanted to give you another example so that you have an alternative architecture to consider. Definitely read up on scopes and closures and the use of this. Also, you don't need jQuery for this function. Only import a large library like jQuery when you need it. In this case document.getElementById does you well, as does addEventListener.
There are even more exciting ways to handle a countdown (including the use of recursion), but below is an example of envisioning your Clock as a single object. This gives you greater control over the clock and it makes it reusable.
You can define functions on the clock that manage the interval, decrement the countdown, pause, resume, start and reset the clock. I added buttons for each so you can see how it would work. Also note that I commented out localStorage to show that it works without storage, but mainly because the snippets in StackOverflow aren't given permission to use localStorage so it would crash, but you can run this code here as is.
var Clock = {
speaking_value: 10,
interval: -1,
countdown: function() {
speaking_value = this.speaking_value;
if (speaking_value <= 0) {
//localStorage.setItem("speaking_counter", 0);
} else {
speaking_value = parseInt(speaking_value) - 1;
//localStorage.setItem("speaking_counter", speaking_value);
}
document.getElementById('overall_time').innerHTML = speaking_value;
if (speaking_value == 0) {
//localStorage.setItem("speaking_counter", speaking_value);
var self = this;
setTimeout(function() {
clearInterval(self.interval);
}, 1000);
}
this.speaking_value = speaking_value;
this.updateClock();
},
paused: false,
pause: function() {
clearInterval(this.interval);
this.paused = true;
},
resume: function() {
if (this.paused) {
this.paused = false;
this.tick();
}
},
updateClock: function() {
speaking_value = this.speaking_value;
var hours = Math.floor(speaking_value / 3600);
var minutes = Math.floor(speaking_value % 3600 / 60);
var seconds = Math.floor(speaking_value % 3600 % 60);
var red_time = hours + ' : ' + minutes + ' : ' + seconds;
document.getElementById('overall_times').innerHTML = red_time;
},
tick: function() {
var self = this;
this.interval = setInterval(function() {
self.countdown()
}, 1000)
},
start: function() {
this.updateClock();
this.tick();
},
reset: function(){
clearInterval(this.interval);
this.speaking_value = 10;
this.updateClock();
}
};
Clock.updateClock();
document.getElementById('startButton').addEventListener('click', function() { Clock.start(); });
document.getElementById('pauseButton').addEventListener('click', function() { Clock.pause(); });
document.getElementById('resumeButton').addEventListener('click', function() { Clock.resume(); });
document.getElementById('resetButton').addEventListener('click', function() { Clock.reset(); });
<div class="div__time">
<div style="display: none;" id="overall_time"></div>
<div id="overall_times"></div>
<div class="total_time"></div>
</div>
<input id="startButton" type="button" value="Start">
<input id="pauseButton" type="button" value="Pause">
<input id="resumeButton" type="button" value="Resume">
<input id="resetButton" type="button" value="Reset">

Related

JavaScript Timer pauses on page reload

I am using a JavaScript code for a timer which works fine with the code below, the only problem is when i refresh the page one second loses.
I need the timer to keep running even if i refresh the page.
I tried to get local time setHours(00) nothing changed.
How do I keep timer running ?
function work(x, id, id_p) {
var span = document.getElementsByClassName('data-work');
for (i = 0; i < span.length; i++) {
var totalsum = span[i].dataset.totalwork;
}
var Clock = {
totalSeconds: parseInt(x),
totalSecondsproject: parseInt(totalsum),
start: function () {
var self = this;
function pad(val) {
return val > 9 ? val : "0" + val;
}
this.interval = setInterval(function () {
self.totalSeconds += 1;
self.totalSecondsproject += 1;
var hour = pad(Math.floor(self.totalSecondsproject / 3600));
var min = pad(Math.floor(self.totalSecondsproject / 60 % 60));
var sec = pad(parseInt(self.totalSecondsproject % 60));
var totat_work = hour + ":" + min + ":" + sec;
var totat_work_db = self.totalSeconds;
$(".totatl_hour_work").text(totat_work);
$.ajax({
type: 'Post',
url: 'includes/function.php',
data: {divVal: totat_work_db, id_interview: id, id_project:id_p}
});
}, 1000);
}
};
$('.startButton').ready(function () {
Clock.start();
var refresh = setInterval(function () {
$(window).attr('location', 'agent_dashboard.php?autorefresh');
}, 300 * 1000);
});
}

Javascript not able to make common functions for a prototype

I am trying to make timer in javascript using a prototype. Each time a new timer is created, a object of prototype is created. There are methods to increase time and print each second. The whole code snippet is as follows:
function Timer(elem) {
this.interval = null;
this.currentTime = {
sec: 0,
min: 0,
hr: 0
};
this.elem = elem;
};
Timer.prototype.start = function() {
var self = this;
if (!self.interval) {
self.interval = setInterval(update, 1000);
}
function update() {
incrementTime();
render();
}
function render() {
self.elem.innerText = getPrintableTime();
}
function incrementTime() {
self.currentTime["min"] += Math.floor((++self.currentTime["sec"]) / 60);
self.currentTime["hr"] += Math.floor(self.currentTime["min"] / 60);
self.currentTime["sec"] = self.currentTime["sec"] % 60;
self.currentTime["min"] = self.currentTime["min"] % 60;
}
function getPrintableTime() {
var text = getTwoDigitNumber(self.currentTime["hr"]) + ":" + getTwoDigitNumber(self.currentTime["min"]) + ":" + getTwoDigitNumber(self.currentTime["sec"]);
return text;
}
function getTwoDigitNumber(number) {
if (number > 9) {
return "" + number;
} else {
return "0" + number;
}
}
};
module.exports = Timer;
I have all methods in start function. The problem is that for each new object of Timer, new space for each method will be used which is very inefficient. But when I try to put methods outside of start function, they lose access to self variable. You can see that there is setInterval function used which will be calling these methods per second. I cannot use this also as this will be instance of Window in subsequent calls.
How can I solve this situation by only keeping one instance of all the interior methods?
You don't need to have all methods in the start function. Yes, for each new Timer instance, new space for each function will be used, but that is necessary when you want to work with setInterval as you need a function which closes over the instance. However, you need only one such closure, the other methods can be standard prototype methods.
function getTwoDigitNumber(number) {
return (number > 9 ? "" : "0") + number;
}
function Timer(elem) {
this.interval = null;
this.currentTime = {
sec: 0,
min: 0,
hr: 0
};
this.elem = elem;
};
Timer.prototype.start = function() {
var self = this;
if (!this.interval) {
this.interval = setInterval(function update() {
self.incrementTime();
self.render();
}, 1000);
}
};
Timer.prototype.render() {
this.elem.innerText = this.getPrintableTime();
};
Timer.prototype.incrementTime = function() {
this.currentTime.sec += 1;
this.currentTime.min += Math.floor(this.currentTime.sec / 60);
this.currentTime.hr += Math.floor(this.currentTime.min / 60);
this.currentTime.sec = this.currentTime.sec % 60;
this.currentTime.min = this.currentTime.min % 60;
};
Timer.prototype.getPrintableTime = function() {
var text = getTwoDigitNumber(this.currentTime.hr) + ":"
+ getTwoDigitNumber(this.currentTime.min) + ":"
+ getTwoDigitNumber(self.currentTime.sec);
return text;
};
module.exports = Timer;
Btw, regarding your incrementTime pattern, you should have a look at How to create an accurate timer in javascript?.
You can use apply to use functions defined outside of prototype with correct this context.
function Timer(elem) {
this.interval = null;
this.currentTime = {
sec: 0,
min: 0,
hr: 0
};
this.elem = elem;
};
function update() {
incrementTime.apply(this);
render.apply(this);
}
function render() {
this.elem.innerText = getPrintableTime.apply(this);
}
function incrementTime() {
this.currentTime["min"] += Math.floor((++this.currentTime["sec"]) / 60);
this.currentTime["hr"] += Math.floor(this.currentTime["min"] / 60);
this.currentTime["sec"] = this.currentTime["sec"] % 60;
this.currentTime["min"] = this.currentTime["min"] % 60;
}
function getPrintableTime() {
var text = getTwoDigitNumber(this.currentTime["hr"]) + ":" + getTwoDigitNumber(this.currentTime["min"]) + ":" + getTwoDigitNumber(this.currentTime["sec"]);
return text;
}
function getTwoDigitNumber(number) {
if (number > 9) {
return "" + number;
} else {
return "0" + number;
}
}
Timer.prototype.start = function() {
var self = this;
if (!self.interval) {
self.interval = setInterval(function() {
update.apply(self);
}, 1000);
}
};
document.addEventListener('DOMContentLoaded', function() {
var timer = new Timer(document.getElementById('timer'));
timer.start();
}, false);
<div id="timer"></div>
If I understand correctly, you're wanting to only create one interval.
One possible solution would be to create a static method and variable to manage the setInterval. I would note that while this may be more performance friendly, the timers will always start and run on the same count...not from the moment each timer is created. (See example)
Of course, you could capture the current timestamp and calculate the elapsed time from there. But, that's another thread ;)
function Timer(elem) {
this.interval = null;
this.currentTime = {
sec: 0,
min: 0,
hr: 0
};
this.elem = elem;
};
Timer.subscribe = function(timer) {
Timer.subscribers = Timer.subscribers || [];
if (Timer.subscribers.indexOf(timer) === -1) {
Timer.subscribers.push(timer);
timer.update.call(timer);
}
Timer.checkInterval();
};
Timer.unsubscribe = function(timer) {
Timer.subscribers = Timer.subscribers || [];
if (Timer.subscribers.indexOf(timer) !== -1) {
Timer.subscribers.splice(Timer.subscribers.indexOf(timer), 1);
}
Timer.checkInterval();
};
Timer.checkInterval = function() {
if (!Timer.interval && Timer.subscribers.length > 0) {
Timer.interval = setInterval(function() {
Timer.subscribers.forEach(function(item) {
item.update.call(item);
});
}, 1000);
} else if (Timer.interval && Timer.subscribers.length === 0) {
clearInterval(Timer.interval);
Timer.interval = null;
}
};
Timer.prototype = {
start: function() {
Timer.subscribe(this);
},
stop: function() {
Timer.unsubscribe(this);
},
update: function() {
this.incrementTime();
this.render();
},
incrementTime: function() {
this.currentTime["min"] += Math.floor((++this.currentTime["sec"]) / 60);
this.currentTime["hr"] += Math.floor(this.currentTime["min"] / 60);
this.currentTime["sec"] = this.currentTime["sec"] % 60;
this.currentTime["min"] = this.currentTime["min"] % 60;
},
render: function() {
var self = this;
function getPrintableTime() {
var text = getTwoDigitNumber(self.currentTime["hr"]) + ":" + getTwoDigitNumber(self.currentTime["min"]) + ":" + getTwoDigitNumber(self.currentTime["sec"]);
return text;
}
function getTwoDigitNumber(number) {
if (number > 9) {
return "" + number;
} else {
return "0" + number;
}
}
this.elem.innerText = getPrintableTime();
}
};
/**
*
*/
var timers = document.getElementById('timers');
function addTimer() {
var el = document.createElement('div');
var tmr = document.createElement('span');
var btn = document.createElement('button');
var t = new Timer(tmr);
btn.innerText = 'Stop';
btn.onclick = function() {
t.stop();
};
el.appendChild(tmr);
el.appendChild(btn);
timers.appendChild(el);
t.start();
};
<div id="timers"></div>
<button onclick="addTimer()">Add Timer</button>

timer implementation in javascript

I had written following code for implementing a timer in JS. But the issue is, for the subsequent recursive calls, the method throws reference error for timeChkSplitTime. How does it happen as its being passed in settimeout().
Also, later I used the easy timer js lib for this. If possible, pls provide an idea to configure the timer for minutes and seconds alone.
function timeChkold(timeChkSplitTime) {
var min = timeChkSplitTime[0], sec = timeChkSplitTime[1];
if (!(timeChkSplitTime[0]==0 && splitTime[1]==0)) {
var strSec, strMin = "0"+min.toString();
if (sec < 10) strSec = "0"+ sec.toString();
else strSec = sec.toString();
$(".timer-btn time").html(strMin+":"+strSec);
timeChkSplitTime[0]=0;
if (sec > 0) timeChkSplitTime[1]--;
else timeChkSplitTime[1] = 59;
setTimeout( "timeChk(timeChkSplitTime);", 1000);
}
else {
var startBtn = $(".start-btn");
startBtn.html("Start");
startBtn.css( {
"border": "1px solid #56B68B",
"background": "#56B68B",
});
var startTime = "01:00";
$(".timer-btn time").html(startTime);
}
}
setTimeout( "timeChk(timeChkSplitTime);", 1000);
should be
setTimeout( timeChk(timeChkSplitTime), 1000);
Variables aren't parsed through strings, on the line with the code:
setTimeout( "timeChk(timeChkSplitTime);", 1000);
It's literally reading the parameter as the value as the text timeChkSplitTime and not the value of the variable timeChkSplitTime. Other than using a string use a function for setTimeout:
setTimeout( timeChk(timeChkSplitTime), 1000);
your code is a little bit of a spaghetti code. you should seperate your code logic from the view. split them into functions. and most importantly, using setTimeout is not efficient in this case.
var CountdownTimer = function(startTime) {
var timeInSeconds = this.stringToSeconds(startTime);
this.original = timeInSeconds;
this.time = timeInSeconds;
this.running = false;
}
CountdownTimer.prototype.start = function(callback) {
this.running = true;
this.interval = setInterval(function() {
if(this.time < 1) {
this.running = false;
clearInterval(this.interval);
} else {
this.time -= 1;
callback();
}
}.bind(this), 1000);
}
CountdownTimer.prototype.pause = function() {
if(this.running) {
this.running = false;
clearInterval(this.interval);
}
}
CountdownTimer.prototype.restart = function() {
this.time = this.original;
}
CountdownTimer.prototype.stringToSeconds = function(timeSting) {
var timeArray = timeSting.split(':');
var minutes = parseInt(timeArray[0], 10);
var seconds = parseInt(timeArray[1], 10);
var totalSeconds = (minutes*60) + seconds;
return totalSeconds;
}
CountdownTimer.prototype.secondsToStrings = function(timeNumber) {
finalString = '';
var minutes = parseInt(timeNumber/60, 10);
var seconds = timeNumber - (minutes*60);
var minStr = String(minutes);
var secStr = String(seconds);
if(minutes < 10) minStr = "0" + minStr;
if(seconds < 10) secStr = "0" + secStr;
return minStr + ":" + secStr;
}
to run this code you can add the following
var countdownTest = new CountdownTimer("01:15");
countdownTest.start(onEachTick);
function onEachTick() {
var time = countdownTest.secondsToStrings(countdownTest.time);
console.log(time)
}
you can write your custom code in the onEachTick funciton.
you can check if the timer is running by typing countdownTest.running.
you can also restart and pause the timer. now you can customize your views however you want.

JS Countdown timer with days:hours:minutes

I found a neat timer but I need to customize it a bit to work for my project, I tried to change javascript code so it would be a countdown until the weekend and start again from ex: 6days:23hours:59minutes, but I failed miserably
I also would like to know how possible could I add a third row called days
http://codepen.io/anon/pen/ZYEBjP
JS code
var Clock = (function(){
var exports = function(element) {
this._element = element;
var html = '';
for (var i=0;i<6;i++) {
html += '<span> </span>';
}
this._element.innerHTML = html;
this._slots = this._element.getElementsByTagName('span');
this._tick();
};
exports.prototype = {
_tick:function() {
var time = new Date();
this._update(this._pad(time.getHours()) + this._pad(time.getMinutes()) + this._pad(time.getSeconds()));
var self = this;
setTimeout(function(){
self._tick();
},1000);
},
_pad:function(value) {
return ('0' + value).slice(-2);
},
_update:function(timeString) {
var i=0,l=this._slots.length,value,slot,now;
for (;i<l;i++) {
value = timeString.charAt(i);
slot = this._slots[i];
now = slot.dataset.now;
if (!now) {
slot.dataset.now = value;
slot.dataset.old = value;
continue;
}
if (now !== value) {
this._flip(slot,value);
}
}
},
_flip:function(slot,value) {
// setup new state
slot.classList.remove('flip');
slot.dataset.old = slot.dataset.now;
slot.dataset.now = value;
// force dom reflow
slot.offsetLeft;
// start flippin
slot.classList.add('flip');
}
};
return exports;
}());
var i=0,clocks = document.querySelectorAll('.clock'),l=clocks.length;
for (;i<l;i++) {
new Clock(clocks[i]);
}
I would create a helper:
var TimeHelper = function(days, hours, minutes, callback) {
this.subtractMinute = function() {
minutes = (minutes + 60 - 1) % 60;
if (minutes === 0) {
hours = (hours + 60 - 1) % 60;
if (hours === 0) {
days = (days + 24 - 1) % 24;
if (days === 0) {
days = 24;
hours = 0;
minutes = 0;
}
}
}
callback(days, hours, minutes);
}
}
function refreshUI(days, hours, minutes) {
//refresh my ui elements
}
var timeHelper = new TimeHelper(24, 0, 0);
And then you can call timeHelper.subtractMinute once/minute this on every minute

I want to make countdown then capatcha

Hi
I got countdown code
<script type="text/javascript">
window.onload = function() {
countDown('my_div1', '<form>1+1=<input name="d" type="text" /></form>', 10);
}
function countDown(elID, output, seconds) {
var elem = document.getElementById(elID),
start = new Date().getTime(), end = start+seconds*1000,
timer = setInterval(function() {
var now = new Date().getTime(), timeleft = end-now, timeparts;
if( timeleft < 0) {
elem.innerHTML = output;
clearInterval(timer);
}
else {
timeparts = [Math.floor(timeleft/60000),Math.floor(timeleft/1000)%60];
if( timeparts[1] < 10) timeparts[1] = "0"+timeparts[1];
elem.innerHTML = "Time left: "+timeparts[1];
}
},250);
}
</script>
I want when the countdown end appear CAPTCHA or question if this right, then continue to link
try to put the countdown function here
window.onload = function() {
countDown('my_div1', //here// , 10);
}
Assume that your countdown coding is working fine and you have a div in which captcha is stored say div id = "captchadiv",
<script type="text/javascript">
window.onload = function() {
//////////////////////////////////////////////////////
set the visibility of the captcha hidden here.
//////////////////////////////////////////////////////
countDown('my_div1', '<form>1+1=<input name="d" type="text" /></form>', 10);
}
function countDown(elID, output, seconds) {
var elem = document.getElementById(elID),
start = new Date().getTime(), end = start+seconds*1000,
timer = setInterval(function() {
var now = new Date().getTime(), timeleft = end-now, timeparts;
if( timeleft < 0) {
elem.innerHTML = output;
clearInterval(timer);
//////////////////////////////////////////////////////
set visibility of captchadiv to visibile.
//////////////////////////////////////////////////////
}
else {
timeparts = [Math.floor(timeleft/60000),Math.floor(timeleft/1000)%60];
if( timeparts[1] < 10) timeparts[1] = "0"+timeparts[1];
elem.innerHTML = "Time left: "+timeparts[1];
}
},250);
}
//////////////////////////////////////////////////////
add a function here to validate the captcha.
If validation succeeds, do success action.
If validation fails, set captcha visibility to hidden and again call the counttDown function.
//////////////////////////////////////////////////////
</script>
EDIT
Check this out. (Untested version)
<script type="text/javascript">
var mathenticate;
window.onload = function() {
countDown('my_div1', '<form>1+1=<input name="d" type="text" /></form>', 10);
}
function countDown(elID, output, seconds) {
var elem = document.getElementById(elID),
start = new Date().getTime(), end = start+seconds*1000,
timer = setInterval(function() {
var now = new Date().getTime(), timeleft = end-now, timeparts;
if( timeleft < 0) {
elem.innerHTML = output;
clearInterval(timer);
mathenticate = {
bounds: {
lower: 5,
upper: 50
},
first: 0,
second: 0,
generate: function()
{
this.first = Math.floor(Math.random() * this.bounds.lower) + 1;
this.second = Math.floor(Math.random() * this.bounds.upper) + 1;
},
show: function()
{
return this.first + ' + ' + this.second;
},
solve: function()
{
return this.first + this.second;
}
};
mathenticate.generate();
var $auth = $('<input type="text" name="auth" />');
$auth
.attr('placeholder', mathenticate.show())
.insertAfter('input[name="name"]');
}
else {
timeparts = [Math.floor(timeleft/60000),Math.floor(timeleft/1000)%60];
if( timeparts[1] < 10) timeparts[1] = "0"+timeparts[1];
elem.innerHTML = "Time left: "+timeparts[1];
}
},250);
}
$('#form').on('submit', function(e){
e.preventDefault();
if( $auth.val() != mathenticate.solve() )
{
alert('wrong answer!');
// If you want to generate a new captcha, then
mathenticate.generate();
}else {
document.location.href = 'http://www.overdir.com';
}
});
</script>

Categories

Resources