Can implement a stopwatch front-end using Javascript where by clicking on Play starts the timer, when the user clicks Pause or close the window should then send a Ajax to the PHP update the current value of the timer in the database. The next time the screen opens, then a request is made Ajax at the PHP to return the current value of the timer that is saved in the bank.
HTML:
<body onload="restore_timer();">
<form name="form">
<input type="text" name="cronometro" value="00:00:00" />
<br />
<button type="button" onclick="timer(this); return false;">Play</button>
</form>
</body>
Javascript:
$(document).ready(function() {
var t = form.cronometro.value;
var hora = t.substring(0, 2);
var minuto = t.substring(3, 5);
var segundo = t.substring(6, 8);
restore_timer = function() {
send_ajax("get_time");
}
var interval;
send_ajax = function(opt) {
$.ajax({
method: "POST",
async: "false",
url: "timer.php",
data: {"opt": opt}
}).done(function(msg) {
if (opt == "get_time") {
if (msg.status == "started") {
$('button').html('Pause');
interval = setInterval('tempo()', 983);
}
form.cronometro.value = msg.time;
t = msg.time;
hora = t.substring(0, 2);
minuto = t.substring(3, 5);
segundo = t.substring(6, 8);
}
});
}
timer = function(obj) {
var html = $(obj).html();
if (html == 'Play') {
interval = setInterval('tempo()', 983);
send_ajax("start_timer");
$(obj).html('Pause');
} else {
clearInterval(interval);
send_ajax("save_time");
$(obj).html('Play');
}
}
tempo = function(){
if (segundo < 59) {
segundo++;
if (segundo < 10)
segundo = "0" + segundo;
} else if (segundo == 59 && minuto < 59) {
segundo = 0 + "0";
minuto++;
if (minuto < 10)
minuto = "0" + minuto;
}
if (minuto == 59 && segundo == 59) {
segundo = 0 + "0";
minuto = 0 + "0";
hora++;
if (hora < 10)
hora = "0" + hora;
}
form.cronometro.value = hora + ":" + minuto + ":" + segundo;
}
});
PHP:
if ($_POST) {
$opt = $_POST['opt'];
$servername = "localhost";
$username = "USUARIO";
$password = "SENHA";
$dbname = "BANCO_DE_DADOS";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($opt == "get_time") {
$sql = "SELECT * FROM time_stamps WHERE id = 1";
$result = $conn->query($sql);
$old_time_stamp;
header('Content-Type: application/json');
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$old_time_stamp = $row["time_stamp"];
}
$date = new DateTime();
$time_stamp = $date->getTimestamp();
echo json_encode(array("status" => "started", "time" => date('H:i:s', ($time_stamp - $old_time_stamp))));
} else {
$sql = "SELECT * FROM timer WHERE id = 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo json_encode(array("time" => $row["time"]));
}
}
}
} elseif ($opt == "start_timer") {
$date = new DateTime();
$time_stamp = $date->getTimestamp();
$sql = "INSERT INTO time_stamps VALUES (1, '{$time_stamp}')";
$result = $conn->query($sql);
} elseif ($opt == "save_time") {
$sql = "SELECT * FROM time_stamps WHERE id = 1";
$result = $conn->query($sql);
$old_time_stamp;
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$old_time_stamp = $row["time_stamp"];
}
}
$sql = "DELETE FROM time_stamps WHERE id = 1";
$result = $conn->query($sql);
$date = new DateTime();
$time_stamp = $date->getTimestamp();
$new_time = explode(":", date('H:i:s', ($time_stamp - $old_time_stamp)));
$sql = "SELECT * FROM timer WHERE id = 1";
$result = $conn->query($sql);
$old_time;
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$old_time = explode(":", $row["time"]);
}
}
$hour = intval($old_time[0] + $new_time[0]);
$minute = intval($old_time[1] + $new_time[1]);
$second = intval($old_time[2] + $new_time[2]);
while ($second >= 60) {
$second = $second - 60;
$minute++;
}
while ($minute >= 60) {
$minute = $minute - 60;
$hour++;
}
if ($second < 10)
$second = "0" . strval($second);
if ($minute < 10)
$minute = "0" . strval($minute);
if ($hour < 10)
$hour = "0" . strval($hour);
$time = "{$hour}:{$minute}:{$second}";
$sql = "UPDATE timer SET time = '{$time}' WHERE id = 1";
$result = $conn->query($sql);
}
$conn->close();
}
Database:
CREATE TABLE timer (
id INT PRIMARY KEY,
time VARCHAR(10) NOT NULL
);
CREATE TABLE time_stamps (
id INT PRIMARY KEY,
time_stamp VARCHAR(255) NOT NULL
);
INSERT INTO timer values (1, "00:00:00");
In this example I have only one record in the table timer, if you
need more will need to change the logic a little, but I believe this
won’t be a problem.
Follows working example.
Heed:
I did not validate the value transited by the requests, if the user changes the HTML in hand and give Pause will send to the bank and save normally.
Keep counting until when? If the page reopens displays the same timer?
– Luis Henrique
Exactly! It counts until a pause or stop! You can continue when you press pause and then play. However, you should never stop counting when you’re in 'play'.
– Lollipop
I would save the timestamp at the time the play is pressed into the bank and would make a stopwatch on the
front-end
, If the user presses pause, calculates the time and saves it in another bank table. If the user closes the page and returns, check if there is already a "timer" for it in the seat and bring the initial value to the front timer.– Luis Henrique
That’s the problem: "... If the user closes the page and returns, check if there is already a "timer" for it in the seat and bring the initial value to the front timer."
– Lollipop
If it’s any page where the user doesn’t always have a unique identifier, I don’t see how it can be done. Oh not be that the stopwatch is not individual, but rather something related to page, and just call an ajax on
onLoad
.– Luis Henrique
Bro, the user presses play and is started. The page will only be closed if: the internet drops, if it closes accidentally... But he should always open the page and see how far he is running his time from his play. And in the end it clicks on stop or pause to be able to stop. Maybe the thing is like you said, check the team and calculate between the beginning and the end, but if it is 3 days or more?
– Lollipop
What’s the problem of being 3 days or more? Play = saved timestamp, Pause = timestamp_current - timestamp_saved and stored in a timer_total table. Play takes the value stored in the timer_total and uses it as the initial value of the stopwatch, Pause repeats the calculation, but now increments the record already saved from the timer_total.
– Luis Henrique
You can give an example as an answer?
– Lollipop
Do you need IE compatibility? If you don’t need it, you can use something based on localStorage
– Guilherme Nagatomo
How do you want the customer to identify? I imagine you want to have a chronometer per user, there is some login?
– Sergio
@Sergio, it will be a stopwatch for each customer, but the focus of the question is on how to continue counting even after a computer shutdown until a cash wipe... Anyway! Help awe!
– Lollipop