Database compatible countdown - javascript

I'm looking to create a 15 min countdown that is being displayed when the button start is pushed, but that it is also accessible from different computers. Meaning it doesn't restart when you refresh, or log in in a different computer.
My logic was something like this...
$start = datetimestamp(h:i:s);
$end = datetimestampt(h:i:s) + 900 ;
$countdown = $end-$start
echo $countdown;
However, the timestamp is giving me a lot of issues, and the $countdown is not live.
I'm thinking this has to be strictly php for it to work with MySQL (so that the timestamp doesn't refresh).
I have this in JavaScript which basically is just a countdown of 15 minutes that gets activated when the button is clicked, however it does restart every time the page is refreshed or accessed from a different computer. And I can't figure out how to store a variable into a database...
var seconds = 900;
var t;
function secondPassed() {
var minutes = Math.round((seconds - 30) / 60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
}
function countdown() {
// starts countdown
secondPassed();
if (seconds != 0) {
seconds--;
t = setTimeout("countdown()", 1000);
changeColor();
}
}
function cdpause() {
// pauses countdown
clearTimeout(t);
};
function cdreset() {
// resets countdown
cdpause();
secondPassed();
};
I appreciate any help or guidance you can give me! I've gone through some tutorials, but it doesn't match the requirements I have. If it matters I'm trying to have different timers that may start at different times and all need to be recorded an displayed.

Simple logic.
When the button is clicked, store the start and end times in the database.
When you are displaying it, use the end time and current time to display the timer. You can use the javascript to display the timer.
In this way, you will be able to show the same timer in different systems without restarting it.
To store a value in the database , google it. There are many tutorials online to help you understand inserting data into mysql database using php

Related

How to save time from a stopwatch and display that time in another html page

function runTimer() {
currentTime = leadingZero(timer[0]) + ":" + leadingZero(timer[1]) + ":" + leadingZero(timer[2]);
theTimer.innerHTML = currentTime;
timer[3]++;
timer[0] = Math.floor((timer[3]/100)/60);
timer[1] = Math.floor((timer[3]/100) - (timer[0] * 60));
timer[2] = Math.floor(timer[3] - (timer[1] * 100) - (timer[0] * 6000));
}
So I am currently working on a Typing Test project in javascript and how my program currently works is that when the user first starts typing up the prompt, the stopwatch timer will start timing the user. Once the user finishes typing the prompt, the stopwatch will stop timing and then the user will be taken to an end page which should display the user's time. However I am having issues with trying to save the user's time. For example if User A finishes the test in 15 secs, the program should save the user's time and then display it in the next page which I will take them to.
I have tried using the localStorage.setItem function but just end up getting [object HTML Element] on my page instead of the score. Below I attached my code related to the timer function of my program. I basically want to save the time of it by using local storage but it won't work.
The simplest solution I have come up with is to send the user's time in the new URL as a parameter. When your timing stops, add this line:
window.location = 'your/new/page/location.html?time=' + time;
time - is the user's time. As you see, the parameter goes after '?' sign. So, on the new page you will be able to get this parameter with this line:
var usersTime = window.location.search.split('=')[1];
Here "search" method takes the part of the URL after '?' sign (including it) - it is going to be "?time=15". And then you split this line with '=' sing as a separator and take the second part, which is the number 15.
The local storage stores items as strings.
Therefor the easiest way would be to store the start time and the end time.
So, when the user starts, call:
window.localStorage.setItem("starttime", Date.now());
and when the user finishes, call:
window.localStorage.setItem("endtime", Date.now());
This will give you 2 timestamps, which you can then use to format your display.
Get the timestamps in your next page with:
starttime = window.localStorage.getItem("starttime");
endtime = window.localStorage.getItem("endtime");
totalseconds = (endtime - starttime) / 1000;
then use totalseconds to work out hours/minutes/seconds etc
If you need to display the timer on the screen as the user is typing, you can just use
totalseconds = (Date.now() - window.localStorage.getItem("starttime")) / 1000;
I've tested this in Chrome and it works fine.

Working on my own Javascript countdown timer/ Pomodoro technique

Since I have been teaching myself how to code in JavaScript by watching tutorials on YouTube and reading Head First Javascript book, I decided to set my own challenge by building something that has been quite effective to me - The Pomodoro technique! I have been using this technique since I have started learning JavaScript. And whilst I was thinking of a JavaScript coding challenge that involves arrays, functions, DOM, etc. I thought why not the Pomodoro technique that can have an array of activities to do during my 5-minute break, a function for the 25 and 5-minute timer and then style it using HTML and CSS. Anyway, here is my code so far...
<script>
function startTimer() {
var timer = document.getElementById("myTimer").innerHTML;
var arr = timer.split(":");
var hour = arr[0];
var min = arr[1];
var sec = arr[2];
if (sec == 0) {
if (min == 0) {
if (hour == 0) {
alert(pushup());
window.location.reload();
return;
}
hour--;
min = 60;
if (hour < 10) hour = "0" + hour;
}
min--;
if (min < 10) min = "0" + min;
sec = 59;
}
else sec--;
if (sec < 10) sec = "0" + sec;
document.getElementById("myTimer").innerHTML = hour + ":" + min + ":" + sec;
setTimeout(startTimer, 1000);
function pushup() {
var minBreak = ["Do 5 push ups!", "Do 10 push ups!", "Do 15 push ups!",
"Do 5 sit ups!", "Do 10 sit ups!", "Do 15 sit ups!",
"Clean room!", "Do laundry!", "Walk dog!" ];
var rand1 = Math.floor(Math.random() * minBreak.length);
var phrase = minBreak[rand1];
alert(phrase)
};
};
</script>
</head>
<body onload="startTimer();">
<p id="myTimer">00:00:10</p>
</body>
I did this step by step creating the pushup function first, which was easy to do, setting alerts on each step so I knew I was going on the right track too. However, startTime function is a copy on a YouTube video. As much as I would have loved to figure this out myself I was struggling hard to set a timer in the browser! The only successful way I can do was use the setInterval method. However, the video was only one minute long and it does not explain how it works. I made sure I gone through line to line to understand how it works, the .split method, why multiple of if statements, etc. Wrote notes down and make sure I understood. Now, when the timer goes off at 10 secs it alerts one of the minBreak chores in random, success! BUT then shows another alert saying "The page says undefined" why is this? And (because I am new to creating this) how would you have written this code? I am thinking to have multiple variables of different chores. So, var pushup will have an array of 1 push up, 2 push up and so on. var situp will have an array of 1 situp, 2 situp and so on. What statements or methods should I use so the math.random can pick one of many different variables arrays randomly instead of being all in one. Not really asking for you to show me a code of how it's done but a route of using for statements, or while, or ifs, etc. sorry if doesn't make sense.. I am new to this! But just trying to make something up on the way and challenge myself, and question myself. but at the same time need a mentor/ teacher to show me the way.
You are getting the undefined message, because you have twice an alert. The second one uses a function return value to display, but that function does not return anything, hence undefined:
alert(pushup());
So the function pushup performs itself an alert, which is like you want it. But then the function returns to the above statement, where the function's result is displayed in an alert. It is undefined.
So you can fix this by just calling the function:
pushup();
As far as I understand this was the only issue to be fixed.

Refresh HTML page every new minute

I have a bit of code, which refreshes my HTML page, everytime there is a new minute i.e. when seconds == 0.
<head>
<script>
function reload(){
location.reload();
}
function refresh(){
var d = new Date();
var s = d.getSeconds();
if (s == 0) {setTimeout(reload(), 1000)};
}
</script> </head>
<body onload="refresh(), setInterval('refresh()',1000)">
However, when it refreshes, it refreshes an infinite amount of times in the time that seconds == 0. I have tried to implement "setTimeout", in order to prevent this from happening - and so that it only refreshes once. However, this did not work and it is still refreshing an infinite amount of times while s == 0. Does anyone have any more ideas to prevent this from happening? Any questions, just ask. Thanks
If I understand correctly, you don't want to refresh after 1 minute from loading but refresh when second = 0.
You don't have to call refresh function constantly via interval.
We have current second. So, if we subtract from minute, we can find remaining seconds to new minute.
60 - d.getSeconds();
Then convert into milliseconds, set timeout, and page will be refresh exactly at new minute.
setTimeout(function() { location.reload() }, 1000 * (60 - d.getSeconds()));
If so important you can consider add/subtract milliseconds with d.getMilliseconds()
For JavaScript, you can simplify this down to:
setTimeout(() => {
window.location.reload(1);
}, 60 * 1000);
However a very simple solution not using JS is
<meta http-equiv="refresh" content="60; URL=https://example.com/">
In general the refreshin is not a nice way to do things. have you considered using asychronous calls and refreshing your DOM with JavaScript instead of reloading the whole page?
However if you want to pursue this route I'd take the current starting time as a base and check from here is 1 second has passed already.
const t0 = performance.now();
function refresh(){
if ((performance.now() - t0) >= 1000) {
location.reload();
}
}
However you'll need to call refresh untill this happens.
As for the "don't understand" comment, I cleand up a litle and I'll add some explanation here:
The first line is outside of all functions, so it sets a variable "globally", as it never changes I use a cosntant (instead of a variable) for speed and readability. It sets the current time in ms insode t0
const t0 = performance.now();
In your funcion I use the same command to get the ms again, and substract the formerly saved ms from it. If the new number is more than 1000 bigger than the original, a second has passed and it can do the reload.
if ((performance.now() - t0) >= 1000) {...

Creating a countdown timer script that instead of a specific date counts the duration of a sound file

I've created a sound installation for an exhibition. The sound file last for 24 hours. What I would like to do is to create a site just for this file. I want it to be as stark and simple as possible. A dark background and a white countdown that start once the file start's streaming and countdowns until the file ends. That's from hour 24 to 00:00.
All the countdown scripts count to an specific date and rarely restart themselves.
Is this even possible?
So if I get it right you want to know how to make a progress bar?
I'd say if you don't want to get too much into the niddy-griddy parts, I'd recommend bootsrap and jquery.
I made an example of something I would do:
http://jsfiddle.net/1tq6scga/3/
//JS
var song_seconds = 10;
c = 0;
i = 0;
var invt = setInterval(function(){
c = i/song_seconds;
c = (Math.round(c * 100 * 100)/100) + '%';
$('.progress-bar').html(c);
$('.progress-bar').css({'width':c});
i++;
if(i === song_seconds + 1) {
clearInterval(invt);
}
}, 1000);
so for you I would make it so that the variable max is the length of the song in seconds. Then I'd wrap this up in a function and do it so once a button play is clicked this code is ran in the background, and when I pause the song then the interval gets cleared.
I really don't wanna write more than this, because it requires coding a whole webpage. But this should be enough to get you started.

Showing a formatted elapsed time

On my upload file page I want to show an elapsed time (how long the user has been uploading the file for) in this format: 00:26, which would be 26 seconds. 17:34 would be 17 minutes 34 seconds, etc.
How could I do this? I have an event that gets called when the upload starts so I can set a Date variable from there, and I also have a function that gets called periodically for me to update the elapsed time.
Thanks.
Manually: Off the top of my head.
var s = 0;
var startTime = new Date();
var interval = setInterval(function(){
s++;
var temps = s%60;
var m = Math.floor(s/60);
document.querySelector("#timebox").innerHTML = ""+m+":"+ (temps>9?"":"0") + temps;
},1000);
Then when it is done uploading... it would need to call
clearInterval(interval);
However I would recommend using something like Moment.js though. Much more robust.
client side I'm guessing.
Sure, setInterval() a counter function that starts on the 'click' of the upload. Your counter function could return to screen a kind of 'progress' - is this what you mean ?

Categories