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 7 years ago.
Improve this question
I currently have a countdown timer that shows hours, mins, seconds. But now I would like to add "days" to it. Can you please show me how you would do that?
Here's the code. I left out the php db query as it's not important.
function Timer(container, timeLeft) {
// get hour, minute and second element using jQuery selector
var hoursContainer = $(container).find('.hour');
var minsContainer = $(container).find('.min');
var secsContainer = $(container).find('.sec');
// hold time left
var currentTimeLeft = timeLeft;
// 1 second = 1000 ms
var secondsForTimer = 1000;
// hold ID value return by setInterval()
var timerInterval;
// call setInteval() only when timeLeft is greater than 0
if (currentTimeLeft == 0) {
return;
} else {
//Call setInterval()function and store ID value to timerInterval.
timerInterval = setInterval(countdown, secondsForTimer);
}
//function being passed to setInterval()
function countdown() {
currentTimeLeft = parseInt(currentTimeLeft - secondsForTimer);
if (currentTimeLeft == 0) {
//stop calling countdown function by calling clearInterval()
clearInterval(timerInterval);
return;
} else {
//calculate hours left
var wholeSeconds = parseInt(currentTimeLeft / 1000,10);
var wholeMinutes = parseInt(currentTimeLeft / 60000,10);
var wholeHours = parseInt(wholeMinutes / 60,10);
//calculate minutes left
var minutes = parseInt(wholeMinutes % 60,10);
//calculate seconds left
var seconds = parseInt(wholeSeconds % 60,10);
//prefix 0 to hour, min and second counter
$(hoursContainer).text((wholeHours < 10 ? "0" : "") + wholeHours + (wholeHours <=0 ? " hr" : " hrs"));
$(minsContainer).text((minutes < 10 ? "0" : "") + minutes + (minutes <=0 ? " min" : " mins"));
$(secsContainer).text((seconds < 10 ? "0" : "") + seconds + (seconds <=0 ? " sec" : " secs"));
}
}
}
<?php
// db query here to get the expiry time from the database
foreach($results as $k => $row) {
$expiry_date = $row['expiry_date'];
$timeLeft = (strtotime($expiry_date) - time()) * 1000;
$counterName = "counter_$k";
?>
<div class="counter <?php echo $counterName; ?>">
<span class="hour">00</span>
<span class="min">00</span>
<span class="sec">00</span>
</div>
<script>
// initiate new timer
var timer = new Timer($('.<?php echo $counterName; ?>'), <?php echo $timeLeft; ?>);
</script>
<?php
}
?>
Try this
function Timer(container, timeLeft) {
// get hour, minute and second element using jQuery selector
var daysContainer = $(container).find('.day');
var hoursContainer = $(container).find('.hour');
var minsContainer = $(container).find('.min');
var secsContainer = $(container).find('.sec');
// hold time left
var currentTimeLeft = timeLeft;
// 1 second = 1000 ms
var secondsForTimer = 1000;
// hold ID value return by setInterval()
var timerInterval;
// call setInteval() only when timeLeft is greater than 0
if (currentTimeLeft == 0) {
return;
} else {
//Call setInterval()function and store ID value to timerInterval.
timerInterval = setInterval(countdown, secondsForTimer);
}
//function being passed to setInterval()
function countdown() {
currentTimeLeft = parseInt(currentTimeLeft - secondsForTimer);
if (currentTimeLeft == 0) {
//stop calling countdown function by calling clearInterval()
clearInterval(timerInterval);
return;
} else {
//calculate hours left
var wholeSeconds = parseInt(currentTimeLeft / 1000,10);
var wholeMinutes = parseInt(currentTimeLeft / 60000,10);
var wholeHours = parseInt(wholeMinutes / 60,10);
var wholeDays = parseInt(wholeHours / 24,10);
//calculate hours left
var hours = parseInt(wholeHours % 24,10);
//calculate minutes left
var minutes = parseInt(wholeMinutes % 60,10);
//calculate seconds left
var seconds = parseInt(wholeSeconds % 60,10);
//prefix 0 to hour, min and second counter
$(daysContainer).text((wholeDays < 10 ? "0" : "") + wholeDays + (wholeDays <=0 ? " day" : " days"));
$(hoursContainer).text((hours < 10 ? "0" : "") + hours + (hours <=0 ? " hr" : " hrs"));
$(minsContainer).text((minutes < 10 ? "0" : "") + minutes + (minutes <=0 ? " min" : " mins"));
$(secsContainer).text((seconds < 10 ? "0" : "") + seconds + (seconds <=0 ? " sec" : " secs"));
}
}
}
Add days container on your loop
<div class="counter <?php echo $counterName; ?>">
<span class="day">00</span>
<span class="hour">00</span>
<span class="min">00</span>
<span class="sec">00</span>
</div>
Fiddle: https://jsfiddle.net/otezz/68d9yb6v/1/
Related
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)); } });
;)
I'm trying to do a simply addition,
Just in order to display some dates so Acutaly
I've done something like that:
while($row = mysql_fetch_assoc($qry)):
echo $req="INSERT INTO `agenda` SET
`code_s`= '".$row['code_s']."',
`titre` ='".$row['titre']."',
`action` ='".$row['action']."',
`libelle`='".$row['libelle']."',
`date_action`='".date('Y-m-d',strtotime('+"'.$row['jour'].'" days'))."',
`qualite`='".$da['qualite']."',
`n_doss`='".mysql_real_escape_string($_GET['n_doss'])."',
`code_client`='".$creance['code_client']."'<br>";
endwhile; };
Amm is in the following line that does not display any mistake:
`date_action`='".date('Y-m-d',strtotime('+"'.$row['jour'].'" days'))."',
What I was trying is to display the date incremented of the number of days contained in the var $row['jour'], but Actualy it just display to me 1970-01-01, so I do not understand why, because all the var have a positive number in that var.
Moreover I have one javascript function:
Like that:
<script type="text/javascript">
function getdate2() {
var items = new Array();
var itemCount = document.getElementsByClassName("datepicker hasDatepicker");
for (var i = 0; i < itemCount.length; i++) {
items[i] = document.getElementById("date" + (i + 1)).value;
}
for (var i = 0; i < itemCount.length; i++) {
items[i] = document.getElementById("date" + (i + 1)).value;
var itemDtParts = items[i].split("-");
var itemDt = new Date(itemDtParts[2], itemDtParts[1] - 1, itemDtParts[0]);
<?php $sql="SELECT * FROM `societe` WHERE `id`=1"; $result=mysql_query($sql) or die; $data=mysql_fetch_assoc($result);?><?php if($data['samedi']==0) {?>
if (itemDt.getDay() == 6) {
itemCount[i].value = (itemDt.getDate() < 9 ? "0" : "")+ (itemDt.getDate()+2)+ "-" + (itemDt.getMonth() < 9 ? "0" : "") + (itemDt.getMonth() + 1) + "-" + itemDt.getFullYear();
}
<?php } ?>
if (itemDt.getDay() == 0) {
itemCount[i].value = (itemDt.getDate() < 9 ? "0" : "")+ (itemDt.getDate()+1)+ "-" + (itemDt.getMonth() < 9 ? "0" : "") + (itemDt.getMonth() + 1) + "-" + itemDt.getFullYear();
}
}
return items;
}
</script>
Actualy this function only incremente dates if a day is a sunday or a satturday, it depens of which is the parameter setting from the database on this line:
<?php $sql="SELECT * FROM `societe` WHERE `id`=1"; $result=mysql_query($sql) or die; $data=mysql_fetch_assoc($result);?><?php if($data['samedi']==0) {?>
if (itemDt.getDay() == 6) {
itemCount[i].value = (itemDt.getDate() < 9 ? "0" : "")+ (itemDt.getDate()+2)+ "-" + (itemDt.getMonth() < 9 ? "0" : "") + (itemDt.getMonth() + 1) + "-" + itemDt.getFullYear();
} ?>
Because sometimes some companies does work on satturday.
I would like to know how to apply this function on the new date, before it is insert to the database?
Is there a way I can apply a javascript function to a none-object item in php?
Receive all my utmost Respect.
Kind regards.
SP.
try this for the php part of the question:
`date_action` = '". date('Y-m-d', strtotime(date("Y-m-d"). "+".$row['jour']."days"))."'
Edit:
`date_action` = '". date('Y-m-d', strtotime(date("Y-m-d"). "+".$row['jour']."days"))."'
I have following javascript code. Its a timer code. Timer stops if quiz is 3 for 3 seconds and starts after 3 seconds for 20 seconds. But this code is not working for if quiz is anything else than 3. Can anyone help me with this?
<script type="text/javascript">
var days = 0
var hours = 0
var minutes = 0
var seconds = 20
var delay_countdown = <?php echo ($quiz == 3) || 0 ; ?>;
function setCount ()
{
document.getElementById("remain").innerHTML = seconds+" seconds";
SD=window.setTimeout( "setCount()", 1000 );
if (delay_countdown) {
return
}
seconds--;
if (seconds < 0){
minutes--;
seconds = 59
}
if (minutes < 0){
hours--;
minutes = 59
}
if (hours < 0){
days--;
hours = 23
}
}
</script>
Your script works for me if $quiz is anything else than 3(if it's 3 delay_countdown will be true and you return the function on the 4th line).
Supply a different delay-time when delay_countdown is true:
SD=window.setTimeout( setCount, (delay_countdown)?3000:1000 );
and set delay_countdown to false before leaving the function:
if (delay_countdown) {
delay_countdown=false;
return;
}
I'm using this stopwatch:
<script language="JavaScript" type="text/javascript">
window.onload = function()
{
stopwatch('Start');
}
<!--
var sec = 0;
var min = 0;
var hour = 0;
function stopwatch(text) {
sec++;
if (sec == 60) {
sec = 0;
min = min + 1; }
else {
min = min; }
if (min == 60) {
min = 0;
hour += 1; }
if (sec<=9) { sec = "0" + sec; }
document.clock.stwa.value = ((hour<=9) ? "0"+hour : hour) + " : " + ((min<=9) ? "0" + min : min) + " : " + sec;
if (text == "Start") { document.clock.theButton.value = "Stop "; }
if (text == "Stop ") { document.clock.theButton.value = "Start"; }
if (document.clock.theButton.value == "Start") {
window.clearTimeout(SD);
return true; }
SD=window.setTimeout("stopwatch();", 1000);
}
function resetIt() {
sec = -1;
min = 0;
hour = 0;
if (document.clock.theButton.value == "Stop ") {
document.clock.theButton.value = "Start"; }
window.clearTimeout(SD);
}
// -->
</script>
and would like to capture the time that the clock is stopped on, and then store it as a PHP variable so that I can insert it into our database along with a load of other PHP variables. Is this possible?
Thanks for any help
Spice up your code with some AJAX. Inside of function resetIt() pass the current timestamp to your php script.
jQuery has a solid AJAX part and nice documentation with examples too.
(Assuming jQuery loaded, up and running)
function resetIt() {
$.ajax({
url: 'your.php',
success: function(response){
alert(response);
}
});
sec = -1;
min = 0;
hour = 0;
if (document.clock.theButton.value == "Stop ") {
document.clock.theButton.value = "Start"; }
window.clearTimeout(SD);
}
your.php (since all you need to save the actual timestamp we won't pass any variable to the PHP part. If you need to add specific variables (from JS) you can add them, of course)
if(mysql_query("INSERT INTO `database` (`stopped`) VALUES (NOW())")) {
echo 'success';
} else {
echo 'failed';
}
die();
I'm trying to develop a web application that mainly uses PHP but i'm using jQuery/Javascript to grab people's Tweets from their URL: http://twitter.com/status/user_timeline/joebloggs.json?count=1&callback=?
The thing is want to run a PHP cron job to grab latest tweets from people who have signed up for my application. But i dont know how to do this with javascript?
Is this possible?
EDIT:
This is the javascript code, can i do this in PHP so i can use a Cron Job?
$(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 javascript method setInterval allows you to pass a method and a number of milliseconds. The method you provide will be executed every number of milliseconds you provided. So if you wanted to grab the latest tweets every 30 seconds, you would call something like this:
setInterval(updateTweets,30000);
This would call the method updateTweets every thirty seconds, where you could use ajax to load up the latest tweets.
For more information on setInterval, you can check out: http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/
The best solution is to re-implement your functionality in PHP:
<?
$url = "http://twitter.com/status/user_timeline/joebloggs.json?count=1&callback=?";
$responseJsonString = file_get_contents($url);
$responseArray = json_decode($responseJsonString, $array=true);
// uncomment this to see what's in the response array:
// print_r($responseArray);
// Now, you can do as you like with $responseArray
And then execute the PHP script via crontab.