I want to make countdown then capatcha - javascript

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>

Related

How do I get my timer to stop, when my 10th and last question has been answered?

The goal I am trying to achieve is to get my timer to stop when all the questions of my quiz has been answered. I have 10 total questions. I have been able to get the timer to start. But getting ot to stop on the click of submit on the 10th question is something I can't figure out.
Let me know if you know what I am doing
StackOverflow said my code was too long... I added my code to codepen. I also included my JS on here.
// variables
var score = 0; //set score to 0
var total = 10; //total nmumber of questions
var point = 1; //points per correct answer
var highest = total * point;
//init
console.log('script js loaded')
function init() {
//set correct answers
sessionStorage.setItem('a1', "b");
sessionStorage.setItem('a2', "a");
sessionStorage.setItem('a3', "c");
sessionStorage.setItem('a4', "d");
sessionStorage.setItem('a5', "b");
sessionStorage.setItem('a6', "d");
sessionStorage.setItem('a7', "b");
sessionStorage.setItem('a8', "b");
sessionStorage.setItem('a9', "d");
sessionStorage.setItem('a10', "d");
}
// timer
// var i = 1;
// $("#startButton").click(function (e) {
// setInterval(function () {
// $("#stopWatch").html(i);
// i++;
// }, 1000);
// });
// $("#resetButton").click(function (e) {
// i = 0;
// });
//hide all questions to start
$(document).ready(function() {
$('.questionForm').hide();
//show question 1
$('#question1').show();
$('.questionForm #submit').click(function() {
//get data attribute
current = $(this).parents('form:first').data('question');
next = $(this).parents('form:first').data('question') + 1;
//hide all questions
$('.questionForm').hide();
//show next question in a cool way
$('#question' + next + '').fadeIn(400);
process('' + current + '');
return false;
});
});
//process answer function
function process(n) {
// get input value
var submitted = $('input[name=question' + n + ']:checked').val();
if (submitted == sessionStorage.getItem('a' + n + '')) {
score++;
}
if (n == total) {
$('#results').html('<h3>Your score is: ' + score + ' out of ' + highest + '!</h3> <button onclick="myScore()">Add Your Name To Scoreboard!</a>')
}
return false;
}
window.yourPoints = function() {
return n;
}
function myScore() {
var person = prompt("Please enter your name", "My First Name");
if (person != null) {
document.getElementById("myScore").innerHTML =
person + " " + score
}
}
// function showTime() {
// var d = new Date();
// document.getElementById("clock").innerHTML = d.toLocaleTimeString();
// }
// setInterval(showTime, 1000);
var x;
var startstop = 0;
window.onload = function startStop() { /* Toggle StartStop */
startstop = startstop + 1;
if (startstop === 1) {
start();
document.getElementById("start").innerHTML = "Stop";
} else if (startstop === 2) {
document.getElementById("start").innerHTML = "Start";
startstop = 0;
stop();
}
}
function start() {
x = setInterval(timer, 10);
} /* Start */
function stop() {
clearInterval(x);
} /* Stop */
var milisec = 0;
var sec = 0; /* holds incrementing value */
var min = 0;
var hour = 0;
/* Contains and outputs returned value of function checkTime */
var miliSecOut = 0;
var secOut = 0;
var minOut = 0;
var hourOut = 0;
/* Output variable End */
function timer() {
/* Main Timer */
miliSecOut = checkTime(milisec);
secOut = checkTime(sec);
minOut = checkTime(min);
hourOut = checkTime(hour);
milisec = ++milisec;
if (milisec === 100) {
milisec = 0;
sec = ++sec;
}
if (sec == 60) {
min = ++min;
sec = 0;
}
if (min == 60) {
min = 0;
hour = ++hour;
}
document.getElementById("milisec").innerHTML = miliSecOut;
document.getElementById("sec").innerHTML = secOut;
document.getElementById("min").innerHTML = minOut;
document.getElementById("hour").innerHTML = hourOut;
}
/* Adds 0 when value is <10 */
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
function reset() {
/*Reset*/
milisec = 0;
sec = 0;
min = 0
hour = 0;
document.getElementById("milisec").innerHTML = "00";
document.getElementById("sec").innerHTML = "00";
document.getElementById("min").innerHTML = "00";
document.getElementById("hour").innerHTML = "00";
}
//adding an event listener
window.addEventListener('load', init, false);
https://codepen.io/rob-connolly/pen/xyJgwx
Any help would be appreciated.
its a pretty simple solution just call the stop function in the if condition of n == total
if (n == total) {
$('#results').html('<h3>Your score is: ' + score + ' out of ' + highest + '!</h3>
<button onclick="myScore()">Add Your Name To Scoreboard!</a>')
stop()
}
https://codepen.io/nony14/pen/VwYREgr
Try using clearInterval() to stop the timer.
https://codepen.io/thingevery/pen/dyPrgwz

Pause and Resume the counting values from localstorage

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">

Coundown cokie set up

I cant figuret how set cookie for my countdownt timeer, that if i refresh page it vill not disapear but vill counting.
i be glad if eny can help. i use jquery 2.1.4 and this java countdown script, but when i refresh page all my coundown timers are lost!
/**
* Created by op on 18.07.2015.
*/
function leadZero (n)
{
n = parseInt(n);
return (n < 10 ? '0' : '') + n;
}
function startTimer(timer_id) {
var timer = $(timer_id);
var time = timer.html();
var arr = time.split(":");
var h = arr[0];
h = h.split(" / ");
h = h[1];
var m = arr[1];
var s = arr[2];
if (s == 0)
{
if (m == 0)
{
if (h == 0)
{
timer.html('')
return;
}
h--;
m = 60;
}
m--;
s = 59;
}
else
{
s--;
}
timer.html(' / '+leadZero(h)+":"+leadZero(m)+":"+leadZero(s));
setTimeout(function(){startTimer(timer_id)}, 1000);
}
function timer (name, time)
{
var timer_name = name;
var timer = $(timer_name);
var time_left = time;
timer.html(' / '+ time);
startTimer(timer_name);
}
$(document).ready(function(){
$('.fid').click(function (e)
{
var timer_name = '.timer_'+$(this).data('fid');
var timer = $(timer_name);
if (timer.html() == '')
{
var time_left = timer.data('timer');
var hours = leadZero(Math.floor(time_left / 60));
var minutes = leadZero(time_left % 60);
var seconds = '00';
timer.html(' / '+hours+':'+minutes+':'+seconds);
startTimer(timer_name);
}
});
$.each($('.tab'), function () {
$(this).click(function () {
$.each($('.tab'), function() {
$(this).removeClass('active');
});
$(this).addClass('active');
$('.list').hide();
$('#content-'+$(this).attr('id')).show();
});
});
if (window.location.hash != '')
{
var tab = window.location.hash.split('-');
tab = tab[0];
$(tab).click();
}
console.log(window.location.hash)
});
It would help if you actually set a cookie.
Setting the cookie would go like:
document.cookie="timer=" + time;
And then call it at the beginning of your code
var time = getCookie("timer");
The getCookie() function is outlined in that link, as well as a base knowledge about them.

Javascript function is not calling from code behind button click

I'M calling javascript function from button click
StringBuilder bldr = new StringBuilder();
bldr.AppendFormat("var Timer = new myTimer({0},{1},'{2}','timerData');", this.timerStartValue, this.TimerInterval, this.txtResult.ClientID);
bldr.Append("Timer.go()");
ClientScript.RegisterStartupScript(this.GetType(), "TimerScript", bldr.ToString(), true);
ClientScript.RegisterHiddenField("timerData", timerStartValue.ToString());
Button code.
<asp:Button ID="Next" runat="server" OnClick="Button1_Click" Text="Next"
Width="58px" />
same code is calling from another button click.
"myTimer" is my javascript function... js code...
<script type="text/javascript">
function myTimer(startVal, interval, outputId, dataField) {
this.value = startVal;
this.OutputCntrl = document.getElementById(outputId);
this.currentTimeOut = null;
this.interval = interval;
this.stopped = false;
this.data = null;
var formEls = document.documentElement;
if (dataField) {
for (var i = 0; i < formEls.length - 1; i++) {
if (formEls[i].name == dataField) {
this.data = formEls[i];
i = formEls.length + 1;
}
}
}
myTimer.prototype.go = function () {
if (this.value > 0 && this.stopped == false) {
this.value = (this.value - this.interval);
if (this.data) {
this.data.value = this.value;
}
var current = this.value;
this.OutputCntrl.innerHTML = this.Hours(current) + ':' + this.Minutes(current) + ':' + this.Seconds(current);
this.currentTimeOut = setTimeout("Timer.go()", this.interval);
}
else {
alert('Time Out!');
//window.location('Index.aspx');
}
}
myTimer.prototype.stop = function () {
this.stopped = true;
if (this.currentTimeOut != null) {
clearTimeout(this.currentTimeout);
}
}
myTimer.prototype.Hours = function (value) {
return Math.floor(value / 3600000);
}
myTimer.prototype.Minutes = function (value) {
return Math.floor((value - (this.Hours(value) * 3600000)) / 60000);
}
myTimer.prototype.Seconds = function (value) {
var hoursMillSecs = (this.Hours(value) * 3600000)
var minutesMillSecs = (this.Minutes(value) * 60000)
var total = (hoursMillSecs + minutesMillSecs)
var ans = Math.floor(((this.value - total) % 60000) / 1000);
if (ans < 10)
return "0" + ans;
return ans;
}
}
Please check updated code..
full Js code i updated now.
If you Used Update Panels Then You can Use:
ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "javascriptFunction();", true);
Other Wise You can Use
ClientScript.RegisterStartupScript
(GetType(),Guid.NewGuid().ToString(), "javascriptFunction();",true);

JavaScript countdown timer not starting

I tried using this JavaScript countdown timer on my page but the timer won't start.
What am I doing wrongly?
var CountdownID = null;
var start_msecond = 9;
var start_sec = 120;
window.onload = countDown(start_msecond, start_sec, "timerID");
function countDown(pmsecond, psecond, timerID) {
var msecond = ((pmsecond < 1) ? "" : "") + pmsecond;
var second = ((psecond < 9) ? "0": "") + psecond;
document.getElementById(timerID).innerHTML = second + "." + msecond;
if (pmsecond == 0 && (psecond-1) < 0) { //Recurse timer
clearTimeout(CountdownID);
var command = "countDown("+start_msecond+", "+start_sec+", '"+timerID+"')";
CountdownID = window.setTimeout(command, 100);
alert("Time is Up! Enter your PIN now to subscribe!");
}
else { //Decrease time by one second
--pmsecond;
if (pmsecond == 0) {
pmsecond=start_msecond;
--psecond;
}
if (psecond == 0) {
psecond=start_sec;
}
var command = "countDown("+pmsecond+", "+psecond+", '"+timerID+"')";
CountdownID = window.setTimeout(command, 100);
}
}
<span style="color:red" name="timerID" id="timerID">91.6</span>
here is what you need to do first
window.onload = countDown(start_msecond, start_sec, "timerID");
should be
window.onload = function () {
countDown(start_msecond, start_sec, "timerID");
}
also you should avoid using a string in your setTimeout function:
CountdownID = window.setTimeout(function () {
countDown(pmsecond,psecond,"timerID");
}, 100);
See here http://jsbin.com/ifiyad/2/edit

Categories

Resources