Javascript tracking script polling - javascript

I have the JS tracking code below:
var jTGateway = "trackingurl";
var jTGatewaySSL = "trackingurl";
var jTDomain = "trackingurl";
var jTUser = "";
var jTPage = "";
var jTProtocol = window.location.protocol;
var jTImage = document.createElement('img');
var jTChatElement; var jTSession; var jTUrl;
jTImage.border = 0;
(function () {
if (jTUser == "") {
var dt = new Date(); var jTCookie = document.cookie.toString();
if (jTCookie.indexOf("jtrack") == -1) { jTSession = parseInt(Math.random() * 1000) + "-" + dt.getTime(); document.cookie = "jtrack=" + jTSession + ";expires=Thu, 31-Dec-2020 00:00:00 GMT; path=/"; }
jTCookie = document.cookie.toString();
if (jTCookie.indexOf('jtrack') == -1) { jTSession = ""; } else {
var s = jTCookie.indexOf("jtrack=") + "jtrack=".length; var e = jTCookie.indexOf(";", s);
if (e == -1) e = jTCookie.length; jTSession = jTCookie.substring(s, e);
}
}
if (jTProtocol == "https:") jTGateway = jTGatewaySSL; if (jTUser != "") jTSession = jTUser; if (jTProtocol == "file:") jTProtocol = "http:";
})();
function jTTrackPage() {
if (jTPage == "") jTPage = escape(window.location);
jTUrl = jTProtocol + "//" + jTGateway + "/jtrack.ashx?u=" + jTSession + "&d=" + jTDomain;
jTUrl += "&p='" + jTPage + "'&r='" + escape(document.referrer) + "'";
jTImage.src = jTUrl;
}
I call it on my page like:
<script type='text/javascript' >
if (typeof jTTrackPage == 'function') jTTrackPage();
</script>
My question is, is it possible to have it make the call every 10 seconds say? To show that the user is still on tha page. How would I go about that. Any pointers appreciated. Thanks!

You could either use setInterval:
window.setInterval(jTTrackPage, 10000); // call it every 10 000 ms = 10 s
or setTimeout:
function trackPage() {
jTTrackPage();
window.setTimeout(trackPage), 10000); // call the function again in 10 000 ms
}
trackPage();
The difference between both is that the first one calls it every 10s, and if one call takes more than 10s (unlikely here) the next one will be triggered just after, without waiting 10s. The second solution solves this problem.
You can clear an interval or a timeout using respectively clearInterval and clearTimeout:
var interval = window.setInterval(jTTrackPage, 10000);
window.clearInterval(interval); // <-- stop it
var timeout = window.setTimeout(trackPage, 10000);
window.clearTimeout(timeout); // <-- stop it

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

Javascript Timers assistance

I am having some issues trying to use the console to modify the time remaining on one site.
I want to be able to set the Time remaining to zero to be able to proceed to the next page.
I believe that the issue is that there are multiple things that need to be set in order to proceed to the next page.
See code below, any help you can provide would be appreciated.
var pageLoaded = 0;
var timerStatus = 'pending';
var secondsRemaining = -1;
var secondsElapsed = -1;
var startTicks = 0;
var errorCount = 0;
var estimatedSecondsRemaining = -1;
var zeroTimeCounter = 0;
var intervalIdUpdateBothTimers;
var nonLinearGuid = null;
$(document).ready(function() {
setInterval('AutoSave()', 120000);
intervalIdUpdateBothTimers = setInterval('UpdateBothTimers()', 1000);
if (timerStatus == 'pending') {
var totaltimeclock = document.getElementById('TotalTimeClock');
if (totaltimeclock != null) {
document.getElementById('TotalTimeClock').innerHTML = '-- \: -- \: --';
}
var timeremainingclock = document.getElementById('TimeRemainingClock');
if (timeremainingclock != null) {
document.getElementById('TimeRemainingClock').innerHTML = '-- \: -- \: --';
}
StartTimer();
}
});
function loaded(i,f) {
if (document.getElementById && document.getElementById(i) != null)
{
f();
}
else if (!pageLoaded) setTimeout('loaded(\''+i+'\','+f+')',100);
}
function SuspendTimer() {
UpdateBothTimers();
if (timerStatus == 'active') {
var data = "s=2&cp=" + this.location.pathname + "&nlg=" + GetNonLinearGuid();
timerStatus = 'suspended';
$.ajax({
type: "POST",
url: "/Courses/ajax/CourseData.aspx",
data: data,
success: displayTime,
async: false
});
clearInterval(intervalIdUpdateBothTimers);
}
}
function AutoSave()
{
if (timerStatus == 'active')
{
SaveTime();
}
}
function SaveTime()
{
var data = '';
if (typeof window.IsScormPage === 'undefined')
{
data = "cp=" + this.location.pathname + "&sp=false";
}
else
{
data = "cp=" + this.location.pathname + "&sp=true";
}
data += "&nlg=" + GetNonLinearGuid();
$.ajax({
type: "POST",
url: "/Courses/ajax/CourseData.aspx",
data: data,
success: displayTime,
async: false
});
}
function StartTimer()
{
timerStatus = 'active';
SetNonLinearGuid();
SaveTime();
}
// Sets the nonLinearGuid with the one in the DOM
// the GUID was generated in the server side and
// passed it to the client side (DOM)
function SetNonLinearGuid()
{
var $nonLinearGuid = $("#nonLinearGuid");
if ($nonLinearGuid === undefined)
{
$nonLinearGuid = $("input[name=nonLinearGuid]");
}
if ($nonLinearGuid.length)
{
nonLinearGuid = $nonLinearGuid.val() || null;
window.nonLinearGuid = window.nonLinearGuid || nonLinearGuid;
}
}
function GetNonLinearGuid() {
var nlg = (window.NonLinearGuid || nonLinearGuid),
admin = getQueryStringByName("admin", parent.window.location.href) || "";
if (admin.toLowerCase() == "d3v") {
printNonLinearGuid(nlg);
}
return nlg;
}
function getQueryStringByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
function displayTime(result)
{
if (result.isOk == false)
{
alert(result.message);
}
else
{
var d = new Date();
startTicks = d.getTime();
secondsRemaining = parseInt($(result).find("SecondsRemaining").text());
secondsElapsed = parseInt($(result).find("SecondsElapsed").text());
redirectUrl = $(result).find("RedirectUrl").text();
var suspendTimer = $(result).find("SuspendTimer").text();
var dataNonLinearGuid = "?nlg=" + GetNonLinearGuid();
if (redirectUrl != "") {
location.href = redirectUrl;
}
isError = $(result).find("Error").text();
if (isError == "true")
{
errorCount++;
if (errorCount > 3)
{
logout();
}
}
isOverworked = $(result).find("IsOverworked").text();
if (isOverworked == "true")
{
location.href = "/Courses/MyAccountNonLinear.aspx" + dataNonLinearGuid;
}
if (suspendTimer.length > 0) {
if ($.trim(suspendTimer).toLowerCase() == "true") {
SuspendTimer();
}
}
}
}
function logout()
{
window.top.location.href = "/Courses/loggedout.aspx";
}
function UpdateBothTimers() {
if (timerStatus != 'active') return;
if (secondsElapsed >= 0)
{
UpdateElapsedTimer();
//secondsElapsed++;
}
if (secondsRemaining >= 0) {
UpdateRemainingTimer();
}
if (estimatedSecondsRemaining <= 0 && zeroTimeCounter == 0) {
zeroTimeCounter++;
SaveTime();
}
}
var lang;
function qt(m,lng) {
$('#timeRemaining').css('display', 'none');
setTimeout("$('#EOMQuiz').submit();", m * 1000);
lang = lng;
setTimeout('updateQ('+ m +')', 1000);
}
function updateQ(m) {
--m;
var text;
if (lang == 'es') {
text = 'Entregar - ' + m + ' segundos restantes para completar la prueba';
}
else {
text = 'Submit - ' + m + ' seconds remaining to complete the quiz';
}
if (m > 0) {
setTimeout('updateQ('+m+')', 990);
}
else
{
$('#eomsubmitDiv').css('background-color', '#FF0000');
text ='Submitting... Please Wait.';
}
if (m <= 10 && m > 0)
{
if (m % 2 == 0)
{
$('#eomsubmitDiv').css('background-color', '#FFFF00');
}
else
{
$('#eomsubmitDiv').css('background-color', '#FFFFAA');
}
}
$('#eomsubmit').attr('value', text);
}
function UpdateElapsedTimer()
{
var s = secondsElapsed + (GetTickDiff()/1000);
UpdateTimer('TotalTimeClock', s, 'UP');
}
function GetTickDiff()
{
var d = new Date();
var tickDiff = d.getTime() - startTicks;
return tickDiff;
}
function UpdateRemainingTimer()
{
var s = secondsRemaining - (GetTickDiff()/1000);
estimatedSecondsRemaining = s;
if (s < 0) s = 0;
UpdateTimer('TimeRemainingClock', s, 'DOWN');
}
function UpdateTimer(ClockID,ElapsedSeconds,ClockDirection){
//check to see if we can run this code yet
if(document.getElementById && document.getElementById(ClockID) != null){
//declare vars
var _Seconds = 0;
var _Minutes = 0;
var _Hours = 0;
//Format Seconds
_Seconds = Math.floor(ElapsedSeconds % 60);
if(_Seconds <= 9) {
_Seconds = "0"+_Seconds;
}
//Format minutes
_Minutes = Math.floor(ElapsedSeconds/60 % 60);
if(_Minutes <= 9) {
_Minutes = "0"+_Minutes;
}
//Format hours
_Hours = Math.floor(ElapsedSeconds/3600 % 60);
if(_Hours <= 9){
_Hours = "0"+_Hours;
}
document.getElementById(ClockID).innerHTML = _Hours + ":" + _Minutes + ":" + _Seconds;
if (timerStatus != 'active')
{
setTimeout('UpdateTimer(\''+ClockID+'\','+ElapsedSeconds+',\''+ClockDirection+'\')',1000);
return;
}
if(ElapsedSeconds > 0 || ClockDirection == "UP"){
if(ClockDirection == "UP")
{
ElapsedSeconds = ElapsedSeconds + 1;
}
else
{
ElapsedSeconds = ElapsedSeconds - 1;
}
//setTimeout('UpdateTimer(\''+ClockID+'\','+ElapsedSeconds+',\''+ClockDirection+'\')',1000);
}
else{
//Timer has hit zero. Lets make sure the next buttons are visible.
$('#next_top').show();
$('#next_bot').show();
}
}
else if(!pageLoaded) //call function again in 100ms
{
//setTimeout('UpdateTimer(\''+ClockID+'\','+ElapsedSeconds+',\''+ClockDirection+'\')',100);
}
}
function DisplayNextButtons(){
$('#next_top').show();
$('#next_bot').show();
}
function hideNextButtons(){
$('#next_top').hide();
$('#next_bot').hide();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I happened to stumble upon the same code. If you were on the same site as me,
I have a potential fix.
Instead of editing the time remaining I setup a script that will click next when the time has expired. I was too lazy to check whether they are checking timestamps server side. Also the server logs will look more similar to a regular user.
Instructions:
Download the following extension for Chrome
https://chrome.google.com/webstore/detail/custom-javascript-for-web/poakhlngfciodnhlhhgnaaelnpjljija?hl=en
Navigate to the site
click the CJS chrome extension button
check "enable cjs for this host"
paste the following JS snippet into the JS box
var t=setInterval(try_hit_next,1000);
function try_hit_next(){
if (estimatedSecondsRemaining <= 0)
window.location = $('#next_top').parent()[0]['href'];
}
click save
1) No needs to assign "setInterval" to a variable t
2) Has somebody tried to make fully automated script for this resource, i mean "driving defensive course" cause it pushes popups with personal questions randomly and besides shows pages with a сourse-related questions (constantly the same), so hope it's gonna be very useful "tool" )
Unfortunately the timers are actually being kept server-side. You can watch a POST to CourseData.aspx and it will return with new values for SecondsRemaining and SecondsElapsed. These new values are used to set the client-side timers. You can change the client side variables all you want but when you move to the next page, another call to CourseData.aspx is done to fetch the server time. So the server's timers rule this entire process.
I believe the only reason you see any JS timers is to provide a (now hidden) simple "time remaining" clock for the user.
However I am willing to bet that there's a way to POST a new time or SecondsRemaining to the CourseData.aspx page, I just don't know what set of post data variables might be needed to do so.

multiple stopwatch in jquery [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I want to make multiples stopwatches in jquery, but the problem is i want the stopwatch the respective stopwatch to sun when we hit the corresponding button, and should stop when we hit button for another stopwatch and that respective stopwatch should start simultaneously, please see the image for reference, i know the question is not so clear, sorry for inconvenience.
thanks in advance.
try this one:
$(document).ready(function() {
(function($){
$.extend({
APP : {
formatTimer : function(a) {
if (a < 10) {
a = '0' + a;
}
return a;
},
startTimer : function(dir) {
var a;
// save type
$.APP.dir = dir;
// get current date
$.APP.d1 = new Date();
switch($.APP.state) {
case 'pause' :
// resume timer
// get current timestamp (for calculations) and
// substract time difference between pause and now
$.APP.t1 = $.APP.d1.getTime() - $.APP.td;
break;
default :
// get current timestamp (for calculations)
$.APP.t1 = $.APP.d1.getTime();
// if countdown add ms based on seconds in textfield
if ($.APP.dir === 'cd') {
$.APP.t1 += parseInt($('#cd_seconds').val())*1000;
}
break;
}
// reset state
$.APP.state = 'alive';
$('#' + $.APP.dir + '_status').html('Running');
// start loop
$.APP.loopTimer();
},
pauseTimer : function() {
// save timestamp of pause
$.APP.dp = new Date();
$.APP.tp = $.APP.dp.getTime();
// save elapsed time (until pause)
$.APP.td = $.APP.tp - $.APP.t1;
// change button value
$('#' + $.APP.dir + '_start').val('Resume');
// set state
$.APP.state = 'pause';
$('#' + $.APP.dir + '_status').html('Paused');
},
stopTimer : function() {
// change button value
$('#' + $.APP.dir + '_start').val('Restart');
// set state
$.APP.state = 'stop';
$('#' + $.APP.dir + '_status').html('Stopped');
},
resetTimer : function() {
// reset display
$('#' + $.APP.dir + '_ms,#' + $.APP.dir + '_s,#' + $.APP.dir + '_m,#' + $.APP.dir + '_h').html('00');
// change button value
$('#' + $.APP.dir + '_start').val('Start');
// set state
$.APP.state = 'reset';
$('#' + $.APP.dir + '_status').html('Reset & Idle again');
},
endTimer : function(callback) {
// change button value
$('#' + $.APP.dir + '_start').val('Restart');
// set state
$.APP.state = 'end';
// invoke callback
if (typeof callback === 'function') {
callback();
}
},
loopTimer : function() {
var td;
var d2,t2;
var ms = 0;
var s = 0;
var m = 0;
var h = 0;
if ($.APP.state === 'alive') {
// get current date and convert it into
// timestamp for calculations
d2 = new Date();
t2 = d2.getTime();
// calculate time difference between
// initial and current timestamp
if ($.APP.dir === 'sw') {
td = t2 - $.APP.t1;
// reversed if countdown
} else {
td = $.APP.t1 - t2;
if (td <= 0) {
// if time difference is 0 end countdown
$.APP.endTimer(function(){
$.APP.resetTimer();
$('#' + $.APP.dir + '_status').html('Ended & Reset');
});
}
}
// calculate milliseconds
ms = td%1000;
if (ms < 1) {
ms = 0;
} else {
// calculate seconds
s = (td-ms)/1000;
if (s < 1) {
s = 0;
} else {
// calculate minutes
var m = (s-(s%60))/60;
if (m < 1) {
m = 0;
} else {
// calculate hours
var h = (m-(m%60))/60;
if (h < 1) {
h = 0;
}
}
}
}
// substract elapsed minutes & hours
ms = Math.round(ms/100);
s = s-(m*60);
m = m-(h*60);
// update display
$('#' + $.APP.dir + '_ms').html($.APP.formatTimer(ms));
$('#' + $.APP.dir + '_s').html($.APP.formatTimer(s));
$('#' + $.APP.dir + '_m').html($.APP.formatTimer(m));
$('#' + $.APP.dir + '_h').html($.APP.formatTimer(h));
// loop
$.APP.t = setTimeout($.APP.loopTimer,1);
} else {
// kill loop
clearTimeout($.APP.t);
return true;
}
}
}
});
$('#sw_start').live('click', function() {
$.APP.startTimer('sw');
});
$('#cd_start').live('click', function() {
$.APP.startTimer('cd');
});
$('#sw_stop,#cd_stop').live('click', function() {
$.APP.stopTimer();
});
$('#sw_reset,#cd_reset').live('click', function() {
$.APP.resetTimer();
});
$('#sw_pause,#cd_pause').live('click', function() {
$.APP.pauseTimer();
});
})(jQuery);
});
DEMO HERE
OR
$(function () {
// Never assume one widget is just used once in the page. You might
// think of adding a second one. So, we adjust accordingly.
$('.stopwatch').each(function () {
// Cache very important elements, especially the ones used always
var element = $(this);
var running = element.data('autostart');
var hoursElement = element.find('.hours');
var minutesElement = element.find('.minutes');
var secondsElement = element.find('.seconds');
var millisecondsElement = element.find('.milliseconds');
var toggleElement = element.find('.toggle');
var resetElement = element.find('.reset');
var pauseText = toggleElement.data('pausetext');
var resumeText = toggleElement.data('resumetext');
var startText = toggleElement.text();
// And it's better to keep the state of time in variables
// than parsing them from the html.
var hours, minutes, seconds, milliseconds, timer;
function prependZero(time, length) {
// Quick way to turn number to string is to prepend it with a string
// Also, a quick way to turn floats to integers is to complement with 0
time = '' + (time | 0);
// And strings have length too. Prepend 0 until right.
while (time.length < length) time = '0' + time;
return time;
}
function setStopwatch(hours, minutes, seconds, milliseconds) {
// Using text(). html() will construct HTML when it finds one, overhead.
hoursElement.text(prependZero(hours, 2));
minutesElement.text(prependZero(minutes, 2));
secondsElement.text(prependZero(seconds, 2));
millisecondsElement.text(prependZero(milliseconds, 3));
}
// Update time in stopwatch periodically - every 25ms
function runTimer() {
// Using ES5 Date.now() to get current timestamp
var startTime = Date.now();
var prevHours = hours;
var prevMinutes = minutes;
var prevSeconds = seconds;
var prevMilliseconds = milliseconds;
timer = setInterval(function () {
var timeElapsed = Date.now() - startTime;
hours = (timeElapsed / 3600000) + prevHours;
minutes = ((timeElapsed / 60000) + prevMinutes) % 60;
seconds = ((timeElapsed / 1000) + prevSeconds) % 60;
milliseconds = (timeElapsed + prevMilliseconds) % 1000;
setStopwatch(hours, minutes, seconds, milliseconds);
}, 25);
}
// Split out timer functions into functions.
// Easier to read and write down responsibilities
function run() {
running = true;
runTimer();
toggleElement.text(pauseText);
}
function pause() {
running = false;
clearTimeout(timer);
toggleElement.text(resumeText);
}
function reset() {
running = false;
pause();
hours = minutes = seconds = milliseconds = 0;
setStopwatch(hours, minutes, seconds, milliseconds);
toggleElement.text(startText);
}
// And button handlers merely call out the responsibilities
toggleElement.on('click', function () {
(running) ? pause() : run();
});
resetElement.on('click', function () {
reset();
});
// Another advantageous thing about factoring out functions is that
// They are reusable, callable elsewhere.
reset();
if(running) run();
});
});
DEMO HERE

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