Time counter with JavaScript or PHP - php

I want to implement a time counter with JavaScript or PHP. I did some looking on Google and tried it, but didn't get the output I need.
Users will enter the time in the textbox provided, then I need to give them a counter from the time they entered.
Example: If I enter 1:27:38 and click on submit, the time should decrease and I should get an alert when it reaches 0.
How can I implement this?

In JavaScript:
<html>
<head>
</head>
<body>
<script language="JavaScript">
<!-- //
var timeleft;
var nextdue;
var tick = 1000;
function parseTime(t) {
var tt = ("0:00:"+t);
tt = tt.split(":").reverse();
return (tt[0] * 1000)+(tt[1] * 60000)+(tt[2] * 3600000);
}
function zeroPad(n) {
if (n<10) return "0"+n;
return ""+n;
}
function makeTime(t) {
if (t<0) return "0:00:00";
var tt=t+999;
return Math.floor(tt/3600000)+":"+
zeroPad(Math.floor(tt/60000)%60)+":"+
zeroPad(Math.floor(tt/1000)%60);
}
function startTimer() {
nextdue = new Date().getTime();
timeleft = parseTime(document.timerform.timerbox.value);
runTimer();
}
function runTimer() {
document.timerform.timerbox.value=makeTime(timeleft);
if (timeleft<=0) alert ("Time's up!");
else {
var timecorr = (new Date().getTime())-nextdue;
if (timecorr>0 && timecorr<3000) {
timeleft -= (tick+timecorr);
nextdue += tick;
if (timeleft<1) setTimeout ("runTimer()",tick+timeleft);
else setTimeout("runTimer()",Math.max(1,tick-timecorr));
}
else {
nextdue=(new Date().getTime())+tick;
timeleft-=tick;
if (timeleft<1) setTimeout ("runTimer()",tick+timeleft);
else setTimeout("runTimer()",tick);
}
}
}
// -->
</script>
<form name="timerform">
Decimal places: <input type="text" name="timerbox" value="0:00:00"></input>
<input type="button" value="Start timer" onClick="startTimer()"></input>
</form>
</body>
</html>

In PHP:
list($hours, $minutes, $seconds) = explode(':', $_POST['time']);
$seconds = $hours * 3600 + $minutes * 60 + $seconds;
for ($i = $seconds; $i > 0; $i--)
{
echo $i;
sleep(1);
flush();
}
echo 'Countdown finished.';

Related

Javascript re-write of js/php music composition program

A while ago, I created (with much help) a program that uses php and javascript to make some ambient music by randomizing an array of .ogg files. Now I am trying to re-write it with js alone.
The new code immediately below does not work (the .ogg files do play properly when clicked individually, but nothing happens when you press the 'start' button, which is the main feature). (The code below that (containing php) does work.) I've been over the new code several times and I think I've got the 'typos'. I'm pretty sure the problem is in the syntax of the window.setTimeout line, but haven't quite figured out how it should be.
Thanks for any help you can offer!
<!DOCTYPE html>
<html>
<head>
<title>Audio Testing</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function getRandInt (min, max)
{
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function shuffle(o)
{
for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
}
</script>
<script type="text/javascript">
var tonesTotal = 150;
function getDelays(tonesTotal)
{
var return_array = array();
for (var i = 0; i < tonesTotal; i++)
{
var r = getRandInt(0, 600);
var delay = r * 1000;
return_array.push(delay);
}
return return_array;
}
var delays = new Array();
delays = getDelays(tonesTotal);
$(document).ready(function()
{
$("#start").click(function()
{
var base = 'sound';
for(var i = 0; i < tonesTotal; i++)
var id = base + ((i + 1) );
window.setTimeout ("document.getElementById('" + id + "').play()", delays[i]);
});
});
</script>
</head>
<body style="background-color: #999;">
<button id="start">Start</button>
<br><br>
<script>
var tonesTotal = 150;
var samples = new Array("tone0.ogg", "tone2.ogg", "tone4.ogg", "tone6.ogg", "tone7.ogg", "tone9.ogg", "tone11.ogg", "tone12.ogg");
for (var i=1; i <= tonesTotal; i++)
{
shuffle (samples);
var samplepick = samples[0];
document.write ("<audio controls id='sound" + i + "'><source src='" + samplepick + "' type='audio/ogg'></audio>");
}
</script>
</body>
</html>
PREVIOUS CODE:
<!DOCTYPE html>
<html>
<head>
<title>Audio Testing</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<?php
//$randC = rand(1,4);
$C = 150;
function getDelays($C)
{
$return_array = array();
for($i = 0; $i < $C; $i++)
{
$r = rand(0, 600);
$delay = $r * 1000;
array_push($return_array, $delay);
}
return $return_array;
}
echo "<script type=\"text/javascript\">\n";
echo "var delays = new Array();";
$delays = getDelays($C);
for($i = 0; $i < sizeof($delays); $i++)
{
echo "delays[" . $i . "] = " . $delays[$i] . ";\n";
}
echo "
$(document).ready(function()
{
$(\"#start\").click(function()
{
var base = 'sound';
for(i = 0; i < $C; i++)
{
var id = base + ((i + 1) );
window.setTimeout (\"document.getElementById('\" + id + \"').play()\", delays[i]);
}
});
});
</script>
";
?>
<style type="text/css">
</style>
</head>
<body style="background-color: #999;">
<button id="start">Start</button>
<br><br>
<?php
$samples = array("tone0.ogg", "tone2.ogg", "tone4.ogg", "tone6.ogg", "tone7.ogg", "tone9.ogg", "tone11.ogg", "tone12.ogg");
for ($i=1; $i<= $C; $i++) {
shuffle ($samples);
$samplepick = $samples[0];
echo '<audio controls id="sound'.$i.'">
<source src='.$samplepick.' type="audio/ogg">
</audio>';
}
?>
</body>
</html>
When I tested it locally I found a Javascript error in the getDelays() function: First line of code should be:
var return_array = new Array();

Redirect to some specific page after ending countdown timer

Is it possible in this code that on finishing the timer it redirects to some specific page automatically.
<blink>
var timestatus = 1;
function time_dec() {
time_left--;
document.getElementById('countdown').innerHTML = time_left;
if (time_left == 0) {
clearInterval(cinterval);
}
}
function resumetime() {
//time_left = 50;
clearInterval(cinterval);
cinterval = setInterval('time_dec()', 1000);
}
function defaultstart() {
time_left = 50;
clearInterval(cinterval);
cinterval = setInterval('time_dec()', 1000);
}
defaultstart();
</script>
</head>
<body>
<span id="countdown">50</span>.
<input type="button" value="stop" id="stopbutton" onclick="stopstarttime()">
</body>
</html>
</blink>
To redirect in javascript, use:
window.location = "http://foo.com/foo";
This will redirect the user to foo.com/foo

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)); } });
;)

Capture javascript stopwatch stop time and store it as php variable

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();

php ajax auto logout with timer

<script type="text/javascript">
var t;
function startTimer(){
t=setTimeout("document.location='../login/logout.php'", 50000);
}
function stopTimer(){
clearTimeout(t);
}
</script>
This is my script for auto logout,
i want to show the countdown timer, How to create and show the timer,
Also i want to make alive when the user hit the body of the page,
Also timer should reset and then restart again when system is idle,
How to make it,
(Timer should show , that is ,
timer should run when people not touching the system ,
if user touch the system then counter should restart )
Use this function:
function timer(elem, starttime, endtime, speed, funktion, count) {
if (!endtime) endtime = 0;
if (!starttime) starttime = 10;
if (!speed) speed = 1;
speed = speed * 1000;
if ($(elem).html() || $(elem).val()) {
if (count == "next" && starttime > endtime) starttime--;
else if (count == "next" && starttime < endtime) starttime++;
if ($(elem).html()) $(elem).html(starttime);
else if ($(elem).val()) $(elem).val(starttime);
if (starttime != endtime && $(elem).html()) setTimeout(function() {
timer(elem, $(elem).html(), endtime, speed / 1000, funktion, 'next');
}, speed);
if (starttime != endtime && $(elem).val()) setTimeout(function() {
timer(elem, $(elem).val(), endtime, speed / 1000, funktion, 'next');
}, speed);
if (starttime == endtime && funktion) funktion();
} else return;
}
Example
timer("#timer", 50, 0, 1, function() {
location.href = "../login/logout.php";
});
my example:
Updated to check if the user is Idle (is set to 2 seconds, this makes testing easier, i'd recommend at least 5 or 10 minutes).
<body onload="setTimeout('startCountDown()',2000);" onmousemove="resetTimer();">
<form name="counter"><input type="text" size="5" name="timer" disabled="disabled" /></form>
<script type="text/javascript">
<!--
// edit startSeconds as you see fit
// simple timer example provided by Thomas
var startSeconds = 10;
var milisec = 0;
var seconds=startSeconds;
var countdownrunning = false
var idle = false;
document.counter.timer.value=startSeconds;
function CountDown()
{
if(idle == true)
{
if (milisec<=0)
{
milisec=9
seconds-=1
}
if (seconds<=-1)
{
document.location='../login/logout.php';
milisec=0
seconds+=1
return;
}
else
milisec-=1;
document.counter.timer.value=seconds+"."+milisec;
setTimeout("CountDown()",100);
}
else
{
return;
}
}
function startCountDown()
{
document.counter.timer.value=startSeconds;
seconds = startSeconds;
milisec = 0
document.counter.timer.style.display = 'block';
idle = true;
CountDown();
document.getElementById("alert").innerHTML = 'You are idle. you will be logged out after ' + startSeconds + ' seconds.';
countdownrunning = false;
}
function resetTimer()
{
document.counter.timer.style.display = 'none';
idle = false;
document.getElementById("alert").innerHTML = '';
if(!countdownrunning)
setTimeout('startCountDown()',2000);
countdownrunning = true;
}
-->
</script>
my code here...after modified a bit...it works for me...
var startSeconds = 10;
var milisec = 0;
var seconds=startSeconds;
var countdownrunning = false
var idle = false;
document.counter.timer.value=startSeconds;
function CountDown()
{
if(idle == true)
{
if (milisec<=0)
{
milisec=9
seconds-=1
}
if (seconds<=-1)
{
document.location='../login/logout.php';
milisec=0
seconds+=1
return;
}
else
seconds-=1;
setTimeout("CountDown()",1000);
}
else
{
return;
}
}
function startCountDown()
{
seconds = startSeconds;
milisec = 0
idle = true;
CountDown();
document.getElementById("alert").innerHTML = 'You are idle. you will be logged out after ' + startSeconds + ' seconds.';
countdownrunning = false;
}
function resetTimer()
{
idle = false;
if(countdownrunning)
setTimeout('startCountDown()',2000);
countdownrunning = true;
}

Categories