Function to stop this Javascript timer - php

I'm new to Javascript, I got this Javascript timer from the net. I'm trying to stop the timer and insert the stopped time into the database if a certain PHP variable is set, but I'm not sure how to stop the timer. Here's the code. I saw this post and sadly, I still can't get it to work. How to stop a timer function from running?
Thanks!
<script type="text/javascript">
/**********************************************************************************************
* CountUp script by Praveen Lobo (http://PraveenLobo.com/techblog/javascript-countup-timer/)
* This notice MUST stay intact(in both JS file and SCRIPT tag) for legal use.
* http://praveenlobo.com/blog/disclaimer/
**********************************************************************************************/
function CountUp(initDate, id){
this.beginDate = new Date(initDate);
this.countainer = document.getElementById(id);
this.numOfDays = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
this.borrowed = 0, this.years = 0, this.months = 0, this.days = 0;
this.hours = 0, this.minutes = 0, this.seconds = 0;
this.updateNumOfDays();
this.updateCounter();
}
CountUp.prototype.updateNumOfDays=function(){
var dateNow = new Date();
var currYear = dateNow.getFullYear();
if ( (currYear % 4 == 0 && currYear % 100 != 0 ) || currYear % 400 == 0 ) {
this.numOfDays[1] = 29;
}
var self = this;
setTimeout(function(){self.updateNumOfDays();}, (new Date((currYear+1), 1, 2) - dateNow));
}
CountUp.prototype.datePartDiff=function(then, now, MAX){
var diff = now - then - this.borrowed;
this.borrowed = 0;
if ( diff > -1 ) return diff;
this.borrowed = 1;
return (MAX + diff);
}
CountUp.prototype.calculate=function(){
var currDate = new Date();
var prevDate = this.beginDate;
this.seconds = this.datePartDiff(prevDate.getSeconds(), currDate.getSeconds(), 60);
this.minutes = this.datePartDiff(prevDate.getMinutes(), currDate.getMinutes(), 60);
this.hours = this.datePartDiff(prevDate.getHours(), currDate.getHours(), 24);
this.days = this.datePartDiff(prevDate.getDate(), currDate.getDate(), this.numOfDays[currDate.getMonth()]);
this.months = this.datePartDiff(prevDate.getMonth(), currDate.getMonth(), 12);
this.years = this.datePartDiff(prevDate.getFullYear(), currDate.getFullYear(),0);
}
CountUp.prototype.addLeadingZero=function(value){
return value < 10 ? ("0" + value) : value;
}
CountUp.prototype.formatTime=function(){
this.seconds = this.addLeadingZero(this.seconds);
this.minutes = this.addLeadingZero(this.minutes);
this.hours = this.addLeadingZero(this.hours);
}
CountUp.prototype.updateCounter=function(){
this.calculate();
this.formatTime();
this.countainer.innerHTML =
" <strong>" + this.hours + "</strong> <small>" + (this.hours == 1? ":" : ":") + "</small>" +
" <strong>" + this.minutes + "</strong> <small>" + (this.minutes == 1? ":" : ":") + "</small>" +
" <strong>" + this.seconds + "</strong> <small>" + "</small>";
var self = this;
setTimeout(function(){self.updateCounter();}, 1000);
}
<?php if(isset($results['calltime'])) {$timevar= date("M d, Y H:i:s",strtotime($results['calltime']));}?>
window.onload=function(){ new CountUp('<?php echo $timevar; ?>', 'counter'); }
//I need a function to stop timer if (isset($results['firstcall_time']))
</script>

In your method updateCounter() You have following statement
setTimeout(function(){self.updateCounter();}, 1000);
make it like following first.
myTimer = setTimeout(function(){self.updateCounter();}, 1000);
and then whenever you want to stop the timer call this method.
clearTimeout(myTimer);
and then record the time.
It uses setTimeout for counting so you have to use clearTimeout for stopping the contdown.
reffer Clear Timeout
Cheers

In the lines:
setTimeout(function(){self.updateNumOfDays();}, (new Date((currYear+1), 1, 2) - dateNow));
And
setTimeout(function(){self.updateCounter();}, 1000);
You can see the recursion is being used, thus the timer keeps running.
So when you want to stop the timer do SOMETHING like this:
var flag = true;
<?php if (isset($results['firstcall_time'])){ ?>
flag = false;
<?php } ?>
And modify your script a little bit as:
setTimeout(function(){if(flag){self.updateNumOfDays();}else{//write code to cleartimeout}}, (new Date((currYear+1), 1, 2) - dateNow));//check for the flag before recursion
And
setTimeout(function(){if(flag){self.updateCounter();}}else{//write code to cleartimeout}, 1000);

He isn't using a timer. He is using setTimeout, but the executing function, is the same method, sort-of like recursion (but strictly speaking, it isn't). So, it's on going. Hope this makes sense.
A timer is implemented like:
// Start
var timerId = setInterval(func() {
// your code to execute
}, 5000);
// Stop
clearInterval(timerId);
I've added a stop method to CountUp. So you should now be able to do this:
// Start
var counter = new CountUp(new Date(), 'div');
// Stop
counter.stop();
Here's the code. I've just hand coded in here, so if there are any typos or something doesn't work then post a comment.
function CountUp(initDate, id){
this.beginDate = new Date(initDate);
this.countainer = document.getElementById(id);
this.numOfDays = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
this.borrowed = 0, this.years = 0, this.months = 0, this.days = 0;
this.hours = 0, this.minutes = 0, this.seconds = 0;
this.daysTimerId = setInterval(this.updateNumOfDays(), this.getDaysTimerInterval());
this.updateTimerId = setInterval(this.updateCounter(), 1000);
}
CountUp.prototype.stop=function(){
clearInterval(this.daysTimerId);
clearInterval(this.updateTimerId);
}
CountUp.prototype.getDaysTimerInterval=function(dt){
var dateNow = dt || new Date();
return (new Date((dateNow.getFullYear()+1), 1, 2) - dateNow));
}
CountUp.prototype.updateNumOfDays=function(){
var dateNow = new Date();
var currYear = dateNow.getFullYear();
if ( (currYear % 4 == 0 && currYear % 100 != 0 ) || currYear % 400 == 0 ) {
this.numOfDays[1] = 29;
}
// var self = this;
// setTimeout(function(){self.updateNumOfDays();}, self.getDaysTimerInterval(dateNow));
}
CountUp.prototype.datePartDiff=function(then, now, MAX){
var diff = now - then - this.borrowed;
this.borrowed = 0;
if ( diff > -1 ) return diff;
this.borrowed = 1;
return (MAX + diff);
}
CountUp.prototype.calculate=function(){
var currDate = new Date();
var prevDate = this.beginDate;
this.seconds = this.datePartDiff(prevDate.getSeconds(), currDate.getSeconds(), 60);
this.minutes = this.datePartDiff(prevDate.getMinutes(), currDate.getMinutes(), 60);
this.hours = this.datePartDiff(prevDate.getHours(), currDate.getHours(), 24);
this.days = this.datePartDiff(prevDate.getDate(), currDate.getDate(), this.numOfDays[currDate.getMonth()]);
this.months = this.datePartDiff(prevDate.getMonth(), currDate.getMonth(), 12);
this.years = this.datePartDiff(prevDate.getFullYear(), currDate.getFullYear(),0);
}
CountUp.prototype.addLeadingZero=function(value){
return value < 10 ? ("0" + value) : value;
}
CountUp.prototype.formatTime=function(){
this.seconds = this.addLeadingZero(this.seconds);
this.minutes = this.addLeadingZero(this.minutes);
this.hours = this.addLeadingZero(this.hours);
}
CountUp.prototype.updateCounter=function(){
this.calculate();
this.formatTime();
this.countainer.innerHTML =
" <strong>" + this.hours + "</strong> <small>" + (this.hours == 1? ":" : ":") + "</small>" +
" <strong>" + this.minutes + "</strong> <small>" + (this.minutes == 1? ":" : ":") + "</small>" +
" <strong>" + this.seconds + "</strong> <small>" + "</small>";
// var self = this;
// setTimeout(function(){self.updateCounter();}, 1000);
}

Here is how I stopped the counter:
I inserted this few lines before "CountUp.prototype.updateCounter=function(){"
var today=new Date();
var start=new Date(2013,10,25,5,35,0); //example: Stop date
diff = start-today;
Then, inside updateCounter function, instead of directly call the setTimeout I added a condition:
if ( ( (this.seconds==0) && (this.minutes==0) (this.hours==0) && (this.days==0) ) || (diff <=0) ) { //on the fly (page is laready open with the counter running) or onload
//Time's up!
} else {
setTimeout(function(){self.updateCounter();}, 1000);
}
So the new code will look like this:
var today=new Date();
var start=new Date(2013,10,25,5,35,0);
diff = start-today;
Counter.prototype.updateCounter=function(){
this.calculate();
this.formatTime();
this.countainer.innerHTML = " <strong>" + this.seconds + "</strong> " + (this.seconds == 1? ":" : ":")+
" <strong>" + this.minutes + "</strong> " + (this.minutes == 1? ":" : ":")+
" <strong>" + this.hours + "</strong> " + (this.hours == 1? ":" : ":")+
" <strong>" + this.days + "</strong> " + (this.days == 1? ":" : "");
var self = this;
if ( ( (this.seconds==0) && (this.minutes==0) (this.hours==0) && (this.days==0) ) || (diff <=0) ) { //on the fly or onload
//Time's up!
} else {
setTimeout(function(){self.updateCounter();}, 1000);
}
}
Hope that will help.
Shams

Related

jQuery ONLY hour and seconds countdown

I have a code not very professional but it does what i want :). The code is basically doing if shop open count for how long if closed count how long left form opening. Now i wanted to style it with jQuery Countdown but i cant find any to just count hours,minutes, maybe seconds. I was trying UNIX countdowns but dunno what i`m doing wrong. I would like to ask you fellow citizens of Stackoverflow to help me out with this.
This is my code ( Just don`t be haters :) )
date_default_timezone_set('Greenwich'); //Fixes my server location
$openingtime = strtotime('06:00'); //Opening time
$closingtime = strtotime('23:10'); //Closing time
$timenow = strtotime('now'); //Current Server Time
$twentyfourhours = "24:00"; //Hours in a day
//echo date('G:i', $openingtime); //Just texting
//echo date('G:i', $closingtime);
//echo date('H:i', $timenow);
//echo $twentyfourhours;// Testing ends here
$openingin = $twentyfourhours - $timenow + $openingtime; //24:00 - 23:20 + 6:00 = How long left for opening
$closingdown = $closingtime - $timenow; //23:10 - 23:20 How long left to close
//If current time value is bigger then closing time then display when the shop will re-open again
if (date('H:i', $timenow) > date('H:i', $closingtime))
{
echo "The shop will be open in ".date('H:i', $openingin)." hours";
}
//If current time value is lower then closing time then display how long the shop will stay open
elseif (date('H:i', $timenow) < date('H:i', $closingtime))
{
echo "The shop will be open for ".date('H:i', $closingdown)." hours";
}
Ok i have managed to found one but now if you will go to My Testing Ground You will notice that the seconds instead of starting countdown from 60 they start from 00,99,98,97,97 and all the way down :( dunno why its happening im attaching JS code
var flipCounter = function(d, options){
// Default values
var defaults = {
value: 0,
inc: 1,
pace: 1000,
auto: true,
tFH: 39,
bFH: 64,
fW: 53,
bOffset: 390
};
var o = options || {},
doc = window.document,
divId = typeof d !== 'undefined' && d !== '' ? d : 'flip-counter',
div = doc.getElementById(divId);
for (var opt in defaults) o[opt] = (opt in o) ? o[opt] : defaults[opt];
var digitsOld = [], digitsNew = [], subStart, subEnd, x, y, nextCount = null, newDigit, newComma,
best = {
q: null,
pace: 0,
inc: 0
};
/**
* Sets the value of the counter and animates the digits to new value.
*
* Example: myCounter.setValue(500); would set the value of the counter to 500,
* no matter what value it was previously.
*
* #param {int} n
* New counter value
*/
this.setValue = function(n){
if (isNumber(n)){
x = o.value;
y = n;
o.value = n;
digitCheck(x,y);
}
return this;
};
/**
* Sets the increment for the counter. Does NOT animate digits.
*/
this.setIncrement = function(n){
o.inc = isNumber(n) ? n : defaults.inc;
return this;
};
/**
* Sets the pace of the counter. Only affects counter when auto == true.
*
* #param {int} n
* New pace for counter in milliseconds
*/
this.setPace = function(n){
o.pace = isNumber(n) ? n : defaults.pace;
return this;
};
/**
* Sets counter to auto-incrememnt (true) or not (false).
*
* #param {bool} a
* Should counter auto-increment, true or false
*/
this.setAuto = function(a){
if (a && ! o.atuo){
o.auto = true;
doCount();
}
if (! a && o.auto){
if (nextCount) clearNext();
o.auto = false;
}
return this;
};
/**
* Increments counter by one animation based on set 'inc' value.
*/
this.step = function(){
if (! o.auto) doCount();
return this;
};
/**
* Adds a number to the counter value, not affecting the 'inc' or 'pace' of the counter.
*
* #param {int} n
* Number to add to counter value
*/
this.add = function(n){
if (isNumber(n)){
x = o.value;
o.value += n;
y = o.value;
digitCheck(x,y);
}
return this;
};
/**
* Subtracts a number from the counter value, not affecting the 'inc' or 'pace' of the counter.
*
* #param {int} n
* Number to subtract from counter value
*/
this.subtract = function(n){
if (isNumber(n)){
x = o.value;
o.value -= n;
if (o.value >= 0){
y = o.value;
}
else{
y = "0";
o.value = 0;
}
digitCheck(x,y);
}
return this;
};
/**
* Increments counter to given value, animating by current pace and increment.
*
* #param {int} n
* Number to increment to
* #param {int} t (optional)
* Time duration in seconds - makes increment a 'smart' increment
* #param {int} p (optional)
* Desired pace for counter if 'smart' increment
*/
this.incrementTo = function(n, t, p){
if (nextCount) clearNext();
// Smart increment
if (typeof t != 'undefined'){
var time = isNumber(t) ? t * 1000 : 10000,
pace = typeof p != 'undefined' && isNumber(p) ? p : o.pace,
diff = typeof n != 'undefined' && isNumber(n) ? n - o.value : 0,
cycles, inc, check, i = 0;
best.q = null;
// Initial best guess
pace = (time / diff > pace) ? Math.round((time / diff) / 10) * 10 : pace;
cycles = Math.floor(time / pace);
inc = Math.floor(diff / cycles);
check = checkSmartValues(diff, cycles, inc, pace, time);
if (diff > 0){
while (check.result === false && i < 100){
pace += 10;
cycles = Math.floor(time / pace);
inc = Math.floor(diff / cycles);
check = checkSmartValues(diff, cycles, inc, pace, time);
i++;
}
if (i == 100){
// Could not find optimal settings, use best found so far
o.inc = best.inc;
o.pace = best.pace;
}
else{
// Optimal settings found, use those
o.inc = inc;
o.pace = pace;
}
doIncrement(n, true, cycles);
}
}
// Regular increment
else{
doIncrement(n);
}
}
/**
* Gets current value of counter.
*/
this.getValue = function(){
return o.value;
}
/**
* Stops all running increments.
*/
this.stop = function(){
if (nextCount) clearNext();
return this;
}
//---------------------------------------------------------------------------//
function doCount(){
x = o.value;
o.value += o.inc;
y = o.value;
digitCheck(x,y);
if (o.auto === true) nextCount = setTimeout(doCount, o.pace);
}
function doIncrement(n, s, c){
var val = o.value,
smart = (typeof s == 'undefined') ? false : s,
cycles = (typeof c == 'undefined') ? 1 : c;
if (smart === true) cycles--;
if (val != n){
x = o.value,
o.auto = true;
if (val + o.inc <= n && cycles != 0) val += o.inc
else val = n;
o.value = val;
y = o.value;
digitCheck(x,y);
nextCount = setTimeout(function(){doIncrement(n, smart, cycles)}, o.pace);
}
else o.auto = false;
}
function digitCheck(x,y){
digitsOld = splitToArray(x);
digitsNew = splitToArray(y);
var diff,
xlen = digitsOld.length,
ylen = digitsNew.length;
if (ylen > xlen){
diff = ylen - xlen;
while (diff > 0){
addDigit(ylen - diff + 1, digitsNew[ylen - diff]);
diff--;
}
}
if (ylen < xlen){
diff = xlen - ylen;
while (diff > 0){
removeDigit(xlen - diff);
diff--;
}
}
for (var i = 0; i < xlen; i++){
if (digitsNew[i] != digitsOld[i]){
animateDigit(i, digitsOld[i], digitsNew[i]);
}
}
}
function animateDigit(n, oldDigit, newDigit){
var speed, step = 0, w, a,
bp = [
'-' + o.fW + 'px -' + (oldDigit * o.tFH) + 'px',
(o.fW * -2) + 'px -' + (oldDigit * o.tFH) + 'px',
'0 -' + (newDigit * o.tFH) + 'px',
'-' + o.fW + 'px -' + (oldDigit * o.bFH + o.bOffset) + 'px',
(o.fW * -2) + 'px -' + (newDigit * o.bFH + o.bOffset) + 'px',
(o.fW * -3) + 'px -' + (newDigit * o.bFH + o.bOffset) + 'px',
'0 -' + (newDigit * o.bFH + o.bOffset) + 'px'
];
if (o.auto === true && o.pace <= 300){
switch (n){
case 0:
speed = o.pace/6;
break;
case 1:
speed = o.pace/5;
break;
case 2:
speed = o.pace/4;
break;
case 3:
speed = o.pace/3;
break;
default:
speed = o.pace/1.5;
break;
}
}
else{
speed = 80;
}
// Cap on slowest animation can go
speed = (speed > 80) ? 80 : speed;
function animate(){
if (step < 7){
w = step < 3 ? 't' : 'b';
a = doc.getElementById(divId + "_" + w + "_d" + n);
if (a) a.style.backgroundPosition = bp[step];
step++;
if (step != 3) setTimeout(animate, speed);
else animate();
}
}
animate();
}
// Creates array of digits for easier manipulation
function splitToArray(input){
return input.toString().split("").reverse();
}
// Adds new digit
function addDigit(len, digit){
var li = Number(len) - 1;
newDigit = doc.createElement("ul");
newDigit.className = 'cd';
newDigit.id = divId + '_d' + li;
newDigit.innerHTML = '<li class="t" id="' + divId + '_t_d' + li + '"></li><li class="b" id="' + divId + '_b_d' + li + '"></li>';
if (li % 2 == 0){
newComma = doc.createElement("ul");
newComma.className = 'cd';
newComma.innerHTML = '<li class="s"></li>';
div.insertBefore(newComma, div.firstChild);
}
div.insertBefore(newDigit, div.firstChild);
doc.getElementById(divId + "_t_d" + li).style.backgroundPosition = '0 -' + (digit * o.tFH) + 'px';
doc.getElementById(divId + "_b_d" + li).style.backgroundPosition = '0 -' + (digit * o.bFH + o.bOffset) + 'px';
}
// Removes digit
function removeDigit(id){
var remove = doc.getElementById(divId + "_d" + id);
div.removeChild(remove);
// Check for leading comma
var first = div.firstChild.firstChild;
if ((" " + first.className + " ").indexOf(" s ") > -1 ){
remove = first.parentNode;
div.removeChild(remove);
}
}
// Sets the correct digits on load
function initialDigitCheck(init){
// Creates the right number of digits
var initial = init.toString(),
count = initial.length,
bit = 1, i;
for (i = 0; i < count; i++){
newDigit = doc.createElement("ul");
newDigit.className = 'cd';
newDigit.id = divId + '_d' + i;
newDigit.innerHTML = newDigit.innerHTML = '<li class="t" id="' + divId + '_t_d' + i + '"></li><li class="b" id="' + divId + '_b_d' + i + '"></li>';
div.insertBefore(newDigit, div.firstChild);
if (bit != (count) && bit % 2 == 0){
newComma = doc.createElement("ul");
newComma.className = 'cd';
newComma.innerHTML = '<li class="s"></li>';
div.insertBefore(newComma, div.firstChild);
}
bit++;
}
// Sets them to the right number
var digits = splitToArray(initial);
for (i = 0; i < count; i++){
doc.getElementById(divId + "_t_d" + i).style.backgroundPosition = '0 -' + (digits[i] * o.tFH) + 'px';
doc.getElementById(divId + "_b_d" + i).style.backgroundPosition = '0 -' + (digits[i] * o.bFH + o.bOffset) + 'px';
}
// Do first animation
if (o.auto === true) nextCount = setTimeout(doCount, o.pace);
}
// Checks values for smart increment and creates debug text
function checkSmartValues(diff, cycles, inc, pace, time){
var r = {result: true}, q;
// Test conditions, all must pass to continue:
// 1: Unrounded inc value needs to be at least 1
r.cond1 = (diff / cycles >= 1) ? true : false;
// 2: Don't want to overshoot the target number
r.cond2 = (cycles * inc <= diff) ? true : false;
// 3: Want to be within 10 of the target number
r.cond3 = (Math.abs(cycles * inc - diff) <= 10) ? true : false;
// 4: Total time should be within 100ms of target time.
r.cond4 = (Math.abs(cycles * pace - time) <= 100) ? true : false;
// 5: Calculated time should not be over target time
r.cond5 = (cycles * pace <= time) ? true : false;
// Keep track of 'good enough' values in case can't find best one within 100 loops
if (r.cond1 && r.cond2 && r.cond4 && r.cond5){
q = Math.abs(diff - (cycles * inc)) + Math.abs(cycles * pace - time);
if (best.q === null) best.q = q;
if (q <= best.q){
best.pace = pace;
best.inc = inc;
}
}
for (var i = 1; i <= 5; i++){
if (r['cond' + i] === false){
r.result = false;
}
}
return r;
}
// http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric/1830844
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function clearNext(){
clearTimeout(nextCount);
nextCount = null;
}
// Start it up
initialDigitCheck(o.value);
};`

Running multiple functions javascript

I currently have a table that is being populated by a MySQL table, in turn i want to take the data from these cells and use them to create a simulated real time update, i have it working however due to having multiple rows im using for loops in the javascript functions and i believe this is causing the other functions not to run and i cannot figure out a way round it.
Javascript Code:
var seconds = 5;
var divid = "status";
var url = "boo.php";
var timeout;
function refreshdiv(){
// The XMLHttpRequest object
var xmlHttp;
try{
xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
}
catch (e){
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
}
catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){
alert("Your browser does not support AJAX.");
return false;
}
}
}
// Timestamp for preventing IE caching the GET request
fetch_unix_timestamp = function()
{
return parseInt(new Date().getTime().toString().substring(0, 10))
}
var timestamp = fetch_unix_timestamp();
var nocacheurl = url+"?t="+timestamp;
// The code...
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4){
document.getElementById(divid).innerHTML=xmlHttp.responseText;
setTimeout('refreshdiv()',seconds*1000);
}
}
xmlHttp.open("GET",nocacheurl,true);
xmlHttp.send(null);
}
// Start the refreshing process
var seconds;
window.onload = function startrefresh(){
setTimeout('refreshdiv()',seconds*1000);
}
function runningtime(int) {
if(int == 0) { //if there is data
console.log("int=0 so no data is present, int: " + int);
} else if(int == 1){
var isRunning = new Array();
isRunning[0] = " ";
for (var i=0; i < 3; i++) {
var bool = 'running' + i;
console.log("Running = " + bool);
running = document.getElementById(bool).innerHTML.substring(10,11);
console.log("running: " + running);
if(isRunning[i] == "1") {
var time = 'Time' + i;
a= document.getElementById(time).innerHTML;
console.log("a= " + a);
hour=a.substring(0,2);
min= a.substring(3,5);
sec= a.substring(6,8);
sec==sec++;
if (min<=9) { min="0"+min; }
if (sec<=9) { sec="0"+sec; }
time = (hour + ":" + min + ":" + sec + " ");
if (document.getElementById) { document.getElementById(time).innerHTML = time; }
else if (document.layers) {
document.layers.theTime.document.write(time);
document.layers.theTime.document.close(); }
} else {
//Do nothing
return;
}
}
timeout = setTimeout("runningtime(1)", 1000);
}
}
function experiencehour(exp) {
if(exp == 0) { //if there is dexphourtexphour
console.log("exp=0 so no data is present, exp: " + exp);
} else if(exp == 1){
var isRunning = new Array();
isRunning[0] = " ";
for (var i=0; i < 3; i++) {
var bool = 'running' + i;
console.log("Running = " + bool);
running = document.getElementById(bool).innerHTML.substring(10,11); //checks if bot running
console.log("running: " + running);
if(isRunning[i] == "1") {
var exph = 'Exph' + i;
var expg = 'Exp' + i;
exphour = document.getElementById(exph).innerHTML; //exphour
currexp = document.getElementById(exp).innerHTML; //current gained exp
exphour =parseInt(exphour);
currexp =parseInt(currexp);
console.log("currexp= " + currexp);
console.log("exphour= " + exphour);
expmin = exphour/60;
console.log("expmin= " + expmin);
expsec = Math.round(expmin/60);
console.log("expsec= " + expsec);
newtotalexp = currexp + expsec;
console.log("newtotalexp= " + newtotalexp);
if (document.getElementById) { document.getElementById(exp).innerHTML = newtotalexp; } //writing new exp
else if (document.lexphouryers) {
document.lexphouryers.theTime.document.write(time);
document.lexphouryers.theTime.document.close(); }
} else {
//Do nothing
return;
}
}
timeout = setTimeout("experiencehour(1)", 1000);
}
}
function variable1hour(var1) {
if(var1 == 0) { //if there is dvar1hourtvar1hour
console.log("var1=0 so no data is present, var1: " + var1);
} else if(var1 == 1){
var isRunning = new Array();
isRunning[0] = " ";
for (var i=0; i < 3; i++) {
var bool = 'running' + i;
console.log("Running = " + bool);
isRunning[i] = document.getElementById(bool).innerHTML.substring(10,11); //checks if bot running
console.log("isRunning = " + isRunning[i]);
if(isRunning[i] == "1") {
var varh = 'Varh' + i;
var varg = 'Var' + i;
console.log("Varh = " + varh);
console.log("Var = " + varg);
var1hour = document.getElementById(varh).innerHTML; //var1hour
currvar1 = document.getElementById(varg).innerHTML; //current gained var1
var1hour =parseInt(var1hour);
currvar1 =parseInt(currvar1);
console.log("currvar1= " + currvar1);
console.log("var1hour= " + var1hour);
var1min = var1hour/60;
console.log("var1min= " + var1min);
var1sec = Math.round(var1min/60);
console.log("var1sec= " + var1sec);
newtotalvar = currvar1 + var1sec;
console.log("newtotalvar= " + newtotalvar);
if (document.getElementById) { document.getElementById(varg).innerHTML = newtotalvar; } //writing new var1
else if (document.lvar1houryers) {
document.lvar1houryers.theTime.document.write(time);
document.lvar1houryers.theTime.document.close();
}
} else {
//Do nothing
return;
}
}
timeout = setTimeout("variable1hour(1)", 1000);
}
}
function stopScript() {
console.log("Stopping script");
clearTimeout(timeout);
}
function startScript(i) {
variable1hour(i);
experiencehour(i);
runningtime(i);
}
Any ideas on how i can get around this so i can get all 3 functions running simultaneously.
I have checked console and im not getting any errors that would stop them from running.
You can't have simultaneously in JS. But you can simulate simultaneous a bit in JS.
Take a look at underscore's defer method.
http://underscorejs.org/#defer
It'd work like this:
Take the loop body and wrap it up in a function
Each iteration through the for loop, make a call to the function using defer
That's basically it. Doing that will allow other functions to "interrupt" any given process (function) and thus "share" the execution thread.
A standard JS implementation w/out defer. I'm trying to simulate the closer of defer. The key takeaway here is that, while the calls still execute in the order that they were queued, all get "started" before any one of them completes. In the case of AJAX async requests, the async response should be able to inject itself between any two loop iterations. You can also set data processing by using slight delays
http://jsfiddle.net/t2z9A/
for(var i = 0; i != 5; ++i)
{
(function(index)
{
document.getElementById('id' + index).innerHTML = 'started...';
setTimeout(function()
{
// kill some time
var str = '';
for(var j = 0; j != 10000000; ++j)
str = str + ' ';
document.getElementById('id' + index).innerHTML = 'Function: 1. Index: ' + index + ' - ' + new Date().getTime();
}, index);
})(i);
}
for(var i = 5; i != 10; ++i)
{
(function(index)
{
document.getElementById('id' + index).innerHTML = 'started...';
setTimeout(function()
{
// kill some time
var str = '';
for(var j = 0; j != 1000000; ++j)
str = str + ' ';
document.getElementById('id' + index).innerHTML = 'Function: 2. Index: ' + index+ ' - ' + new Date().getTime();
}, 1);
})(i);
}

why is this jQuery not working?

I'm having this jQuery script thats adding a timer when someone voted he needs to wait 3 minutes
the script is working till the moment I'm getting the remaining time with php
$(document).ready(function(){
alert("1");
function Timer(dur, par, can, cnt) {
var parent = $(par),
canvas = can ? $(can, parent)[0] : $('.timer', parent)[0],
seconds = cnt ? $(cnt, parent)[0] : $('.counter', parent)[0],
sec = dur,
countdown = sec;
if (!canvas)
canvas = $("<canvas>").addClass('timer')
.attr('width', 100).attr('height', 100).appendTo(parent)[0];
if (!seconds)
seconds = $("<span>").addClass('counter').appendTo(parent)[0];
var ctx = canvas.getContext('2d');
ctx.lineWidth = 8;
ctx.strokeStyle = "#528f20";
var startAngle = 0,
time = 0,
intv = setInterval(function() {
var endAngle = (Math.PI * time * 2 / sec);
ctx.arc(65, 35, 30, startAngle, endAngle, false);
ctx.clearRect(0, 0, 200, 200);
startAngle = endAngle;
ctx.stroke();
countdown--;
if (countdown > 60) {
seconds.innerHTML = Math.floor(countdown / 60);
var ss = countdown % 60;
if (ss < 10)
ss = "0" + ss;
seconds.innerHTML += ":" + ss;
}
else {
seconds.innerHTML = countdown;
}
if (++time > sec, countdown == 0) {
clearInterval(intv);
$(canvas).remove();
$(seconds).remove();
/*$(par).prepend('<img id="theImg" src="http://ivojonkers.com/votify/upvote.png" />');*/
}
}, 1000);}
$(".upvote").click(function(){
alert("2");
var par = $("<div>").addClass("time").appendTo("#timers");
Timer(Math.round(180), par);
});
if (<?php echo $wait; ?> > 0) {
var par = $("<div>").addClass("time").appendTo("#timers");
Timer(Math.round(<?php echo $wait; ?>, par); } });
so in this part I'm getting the time to wait for the next vote with php and this does not seem to work what's going wrong ?
if (<?php echo $wait; ?> > 0) {
var par = $("<div>").addClass("time").appendTo("#timers");
Timer(Math.round(<?php echo $wait; ?>, par); } });
You should just use a setTimeout(function(){},(3 * 60 * 1000)) to block the vote functionality.
//Block the vote here
setTimeout(function(){/*unblock here*/},(3 * 60 * 1000))
Replace this:
Timer(Math.round(<?php echo $wait; ?>, par); } });
With:
Timer(Math.round(<?php echo $wait; ?>, par)); } });
;)

Redirect to homepage from splash page magento

I am trying to redirect to my homepage from a splash (age verification) page, and it just keeps popping up the same age verification page.
I have the ageVerify.php script in the root folder and I have the other script at the top of my template file page. I just need to find the correct file structure format to redirect too after someone hits "yes i'm 18"
The code below doesn't work when added to the top of my column1.phtml file - it just keeps going back and recalling the verify.php script. Any ideas would be very helpful!
<?php
function verified()
{
$redirect_url='http://www.johnsoncreeksmokejuice.com.vhost.zerolag.com/verify.php';
$expires=-1;
session_start();
$validated=false;
if (!empty($_COOKIE["verified"])) {
$validated=true;
}
if (!$validated && isset($_SESSION['verified'])) {
$validated=true;
}
if (is_numeric($expires) && $expires==-1 && !isset($_SESSION['verified'])) {
$validated=false;
}
if ($validated) {
return;
}
else {
$redirect_url=$redirect_url."?return=index.php&x=".$expires;
Header('Location: '.$redirect_url);
exit(0);
}
}
verified();
?>
If $_SESSION is not set always will evaluate this
if (is_numeric($expires) && $expires==-1 && !isset($_SESSION['verified'])) {
$validated=false;
}
Just fix it and should work.
Assuming that everything else is fine, I would replace
if (!empty($_COOKIE["verified"])) {
$validated=true;
}
if (!$validated && isset($_SESSION['verified'])) {
$validated=true;
}
if (is_numeric($expires) && $expires==-1 && !isset($_SESSION['verified'])) {
$validated=false;
}
By:
if ( (isset($_COOKIE["verified"] && !empty($_COOKIE["verified"])) OR isset($_SESSION['verified']) ) {
$validated=true;
}
So, if user has a non-empty "verified" cookie or a "verified" session set, it assumes he is validated.
Chose to use a javascript alternative. Worked out much easier for me:
function writeCookie(key,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = key+"="+value+expires+"; path=/";
}
function readCookie(key) {
var nameEQ = key + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function ageGate() {
var monthDays = {
1: 31,
2: 29,
3: 31,
4: 30,
5: 31,
6: 30,
7: 31,
8: 31,
9: 30,
10: 31,
11: 30,
12: 31
};
var months = {
1: 'January',
2: 'February',
3: 'March',
4: 'April',
5: 'May',
6: 'June',
7: 'July',
8: 'August',
9: 'September',
10: 'October',
11: 'November',
12: 'December'
};
var monthOptions = [];
var dayOptions = {};
var yearOptions = [];
for (var month in monthDays) {
var days = monthDays[month];
monthOptions.push('<option value="' + month + '">' + months[month] + '</option>');
dayOptions[month] = [];
for (var i=1; i <= days; i++) {
var day = i;
dayOptions[month].push('<option value="' + day + '">' + day + '</option>');
}
}
var currentYear = new Date();
currentYear = currentYear.getFullYear();
var startYear = currentYear - 120;
for (var y=currentYear; y > startYear; y--) {
yearOptions.push('<option value="' + y + '">' + y + '</option>');
}
$s(document).ready(function(){
var monthHtml = '';
for (var j=0; j < monthOptions.length; j++) {
var html = monthOptions[j];
monthHtml += html;
}
$s('#ageMonth').html(monthHtml);
var yearHtml = '';
for (var i=0; i < yearOptions.length; i++) {
yearHtml += yearOptions[i];
}
$s('#ageYear').html(yearHtml);
$s('#ageMonth').bind('change', function(){
var dayHtml = '';
var month = $s(this).val();
for (var i=0; i < dayOptions[month].length; i++) {
dayHtml += dayOptions[month][i];
}
$s('#ageDay').html(dayHtml);
});
$s('#ageEnterSite').click(function(e){
e.preventDefault();
var date = new Date();
date.setMonth($s('#ageMonth').val() - 1);
date.setDate($s('#ageDay').val());
date.setYear($s('#ageYear').val());
var maxDate = new Date();
// alert(maxDate.getFullYear());
maxDate.setYear(maxDate.getFullYear() - 18);
if (date <= maxDate) {
writeCookie('jcsj_age_verified', '1', 30);
$s('#age-gate').fadeOut(function(){
$s(this).remove();
$s('body').removeClass('age-gate-visible');
});
}
else {
window.location.href = 'http://google.com';
}
});
$s('#ageMonth').change(); // load default month
// $s('#ageDay').prop('disabled', true);
setTimeout(function(){
$s('body').addClass('age-gate-visible');
$s('#age-gate').fadeIn();
}, 200);
});
}
if (readCookie('jcsj_age_verified')) {
} else {
ageGate();
}
</script>

Can this jQuery/Javascript functionality be replicated with PHP

This is the code to grab tweets, but i need this in PHP, can anybody offer any insight?
$(document).ready( function() {
var url = "http://twitter.com/status/user_timeline/joebloggs.json?count=1&callback=?";
$.getJSON(url,
function(data){
$.each(data, function(i, item) {
$("#twitter-posts").append("<p>" + item.text.linkify() + " <span class='created_at'>" + relative_time(item.created_at) + " via " + item.source + "</span></p>");
});
});
});
String.prototype.linkify = function() {
return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
return m.link(m);
});
};
function relative_time(time_value) {
var values = time_value.split(" ");
time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
var parsed_date = Date.parse(time_value);
var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
delta = delta + (relative_to.getTimezoneOffset() * 60);
var r = '';
if (delta < 60) {
r = 'a minute ago';
} else if(delta < 120) {
r = 'couple of minutes ago';
} else if(delta < (45*60)) {
r = (parseInt(delta / 60)).toString() + ' minutes ago';
} else if(delta < (90*60)) {
r = 'an hour ago';
} else if(delta < (24*60*60)) {
r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
} else if(delta < (48*60*60)) {
r = '1 day ago';
} else {
r = (parseInt(delta / 86400)).toString() + ' days ago';
}
return r;
}
function twitter_callback ()
{
return true;
}
The most complicated part is the request to twitter, you can do something like that:
$content = file_get_contents("http://twitter.com/status/user_timeline/joebloggs.json?count=1&callback=?");
$twitter_response = json_decode($content);
foreach($twitter_response as $item){
//format someway
$item->text; #get the text of each tweet
}
You can use cURL to access the file. Then use the PHP function json_decode to work with the data.
PHP: cURL
PHP: json_decode
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://twitter.com/status/user_timeline/joebloggs.json?count=1&callback=?");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
$json = json_decode($result);
var_dump($json);
Yes you can do it. For the major parts you can use cURL or file_get_contents to fetch the data, json_decode to parse it.

Categories