I tried to show/increment the only time(Hours, Minutes and Seconds) like a timer from getting server side, but it's not working for me.
For this I tried below code.
Can you please help me to run the specified time (Server Time) to run as Timer.
What I have tried:
c#
ScriptManager.RegisterStartupScript(Page, this.GetType(), "close", "OnRunnTimer("+0.21023+");", true);
// JS COde
//Server time I am sending serverTimeP = 0.21023
function OnRunnTimer(timeP) {
setInterval(function () { runJSTimer(timeP); }, 1000);
}
function runJSTimer(serverTimeP) {
var d = new Date();
d.setHours(serverTimeP);
var hours = d.getHours();
var min = d.getMinutes();
var sec = d.getSeconds();
lblJsTimer.SetText(hours + ":" + min + ":" + sec);
}
Can you please help on this.
I'm not sure if I understood, but this is my example of solution to what I think to be your issue.
<body>
<h2 id="timeLabel">Time Label!</h2>
<script type="text/javascript">
var hours = 0;
var min = 0;
var sec = 0;
var serverTime = '2021-02-17T14:34:14.426Z'; // server time example in ISO format
var refreshTimeLabel = function(){
document.getElementById("timeLabel").innerHTML = hours + ":" + min + ":" + sec;
}
var refreshVariables = function () {
var serverTimeDate = new Date(serverTime);
var updatedServerTimeInMilliseconds = serverTimeDate.getTime() + (1000);
var updatedServerTimeDate = new Date(updatedServerTimeInMilliseconds);
serverTime = updatedServerTimeDate.toISOString();
hours = updatedServerTimeDate.getHours();
min = updatedServerTimeDate.getMinutes();
sec = updatedServerTimeDate.getSeconds();
}
var startTimer = function() {
setInterval(function () {
refreshVariables();
refreshTimeLabel();
}, 1000);
}
startTimer();
</script>
</body>
Variant for multiple rows
<body>
<h2 id="timeLabel">Time Label!</h2>
<script type="text/javascript">
var serverTimes = ['2021-02-17T16:34:45.426Z', '2021-02-17T14:54:14.426Z', '2021-02-17T14:00:00.426Z']; // server time array example in ISO format
var refreshServerTimeByIndex = function (index) {
var serverTime = serverTimes[index];
var serverTimeDate = new Date(serverTime);
var updatedServerTimeInMilliseconds = serverTimeDate.getTime() + (1000);
var updatedServerTimeDate = new Date(updatedServerTimeInMilliseconds);
serverTimes[index] = updatedServerTimeDate.toISOString();
}
var refreshServerTimes = function(){
var i;
for(i = 0; i < serverTimes.length; i++){
refreshServerTimeByIndex(i);
}
}
var getTimeTextByDateISO = function(dataISO){
var date = new Date(dataISO);
var hours = date.getHours();
var min = date.getMinutes();
var sec = date.getSeconds();
return hours + ":" + min + ":" + sec;
}
var refreshTimeLabel = function(){
var textLabel = "";
var i;
for(i = 0; i < serverTimes.length; i++){
textLabel += " | " + getTimeTextByDateISO(serverTimes[i]);
}
document.getElementById("timeLabel").innerHTML = textLabel;
}
var startTimer = function() {
setInterval(function () {
refreshServerTimes();
refreshTimeLabel();
}, 1000);
}
startTimer();
</script>
</body>
Related
I need a alert when the countdown hits 00:00:00
<p>
<span id="hms">00:00:05</span>
</body>
<script>
var startTime;
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
} // credits kirlich #http://stackoverflow.com/questions/10730362/get-cookie-by-name
function count() {
if(typeof getCookie('remaining')!= 'undefined')
{
startTime = getCookie('remaining');
}
else if(document.getElementById('hms').innerHTML.trim()!='')
{
startTime = document.getElementById('hms').innerHTML;
}
else
{
var ddddd = new Date();
var hhhhh=ddddd.getHours();
var mmmmm=ddddd.getMinutes();
var sssss=ddddd.getSeconds();
startTime = hhhhh+':'+mmmmm+':'+sssss;
//OR
startTime = ddddd.toTimeString().split(" ")[0]
}
var pieces = startTime.split(":");
var time = new Date();
time.setHours(pieces[0]);
time.setMinutes(pieces[1]);
time.setSeconds(pieces[2]);
var timediff = new Date(time.valueOf()-1000)
var newtime = timediff.toTimeString().split(" ")[0];
document.getElementById('hms').innerHTML=newtime ;
document.cookie = "remaining="+newtime;
setTimeout(count,1000);
}
count();
</script>
</p
<script src="http://code.jquery.com/jquery-latest.js"></script>
<p>
<span id="hms">00:00:05</span>
</body>
<script>
var startTime;
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2)
return parts.pop().split(";").shift();
} // credits kirlich #http://stackoverflow.com/questions/10730362/get-cookie-by-name
function count() {
var check = $("#hms").text();
if (check == "00:00:00") {
myfunction();
}
if (typeof getCookie('remaining') != 'undefined')
{
startTime = getCookie('remaining');
} else if (document.getElementById('hms').innerHTML.trim() != '')
{
startTime = document.getElementById('hms').innerHTML;
} else
{
var ddddd = new Date("00:00:05");
var hhhhh = ddddd.getHours();
var mmmmm = ddddd.getMinutes();
var sssss = ddddd.getSeconds();
startTime = hhhhh + ':' + mmmmm + ':' + sssss;
//OR
startTime = ddddd.toTimeString().split(" ")[0]
}
var pieces = startTime.split(":");
var time = new Date();
time.setHours(pieces[0]);
time.setMinutes(pieces[1]);
time.setSeconds(pieces[2]);
var timediff = new Date(time.valueOf() - 1000)
var newtime = timediff.toTimeString().split(" ")[0];
document.getElementById('hms').innerHTML = newtime;
document.cookie = "remaining=" + newtime;
setTimeout(count, 1000);
}
count();
function myfunction() {
alert("Time Up");
}
</script>
</p
Use this code.
I have a function called save with this code, it's meant to save data from a timer.
The class with the Model is this:
var Schema = mongoose.Schema;
var Timer = new Schema({
Time: {type: Number},
Desc: {type: String},
Doc: {type: String}
});
Timer.statics.findByDesc = function(value, callback){
this.find({ Desc: {"$regex": value, "$options": "i"}}, callback);
}
Timer.statics.findByDoc = function(value, callback) {
this.find({ Doc: { "$regex": value, "$options": "i" }}, callback);
}
Timer.statics.findAll = function(callback){
this.find({}, callback);
}
module.exports = mongoose.model('Timer', Timer);
the model is defined by this code which is imported with:
var Timer = require('./../../models/timer');
but I'm testing it with constants in a function which is called by clicking button, this is the code inside the function:
var newTimer = new Timer({
Time: 6000, Desc: "My first timertest!", Doc: "Test's Dossier"
});
newTimer.save();
however with trial and error I have figured out that it never calls newTimer.save(), it seems to get stuck somewhere without ever leaving the var newTimer = new Timer() function.
I have tried my Timer Model code in other files with code like:
/**
* Created by kevin on 08/03/2016.
*/
var Timer = require('../models/timer'),
mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/legalapp');
mongoose.connection.on('open', function() {
console.log('Mongoose connected.');
});
var newTimer = new Timer({
Time: 5000, Desc: "My first timertest!", Doc: "Test's Dossier"
});
console.log(newTimer.Time);
console.log(newTimer.Desc);
console.log(newTimer.Doc);
newTimer.save();
mongoose.connection.close();
and this did work, so after 3 hours of trying, I'm going crazy, so I came here.
I am using javascript, nodeJS, jquery and mongoose in my project.
Here is the entire file:
var timers = [], Timer = require('./../../models/timer');
function timer(id){
this.id = id;
this.running = false;
this.start = new Date();
this.current = new Date();
this.paused = new Date();
this.timed = 0;
this.desc = "";
this.pauseTime = 0;
this.pauseTimeBuffer = 0;
this.prevTimed = 0;
this.first = true;
this.h = Math.floor(this.timed / 1000 / 60 / 60);
this.timed -= this.h * 1000 * 60 * 60;
this.h = checkTime(this.h);
this.m = Math.floor(this.timed / 1000 / 60);
this.timed -= this.m * 1000 * 60;
this.m = checkTime(this.m);
this.s = Math.floor(this.timed / 1000);
this.timed -= this.s * 1000;
this.s = checkTime(this.s);
}
function startTime(timer){
if(!timer.running) {
if (timer.first) {
timer.start = new Date();
timer.first = false;
}
timer.running = true;
time(timer);
}
}
function stopTime(timer){
if(timer.running) {
if (timer.pauseTime === 0) {
timer.paused = new Date();
} else {
timer.paused = new Date();
timer.pauseTimeBuffer = timer.pauseTime;
}
timer.running = false;
time(timer);
}
}
function save(timer){
//stopTime(timer);
/*var desc = prompt("Enter the description of this task", timer.desc);
var dossier = prompt("What dossier does this timer belong to?");
var current = new Date();
var timed = timer.current - timer.start;
timed -= timer.pauseTime;
*/
var newTimer = new Timer();
newTimer.Time = 6000;
newTimer.Desc = "My first timertest!";
newTimer.Doc = "Test's Dossier";
newTimer.save();
alert("yay");
}
function time(timer) {
if(timer.running) {
var name = '#timer' + timer.id;
var $time = $('' + name);
timer.current = new Date();
timer.timed = timer.current - timer.start;
timer.timed -= timer.pauseTime;
timer.h = Math.floor(timer.timed / 1000 / 60 / 60);
timer.timed -= timer.h * 1000 * 60 * 60;
timer.h = checkTime(timer.h);
timer.m = Math.floor(timer.timed / 1000 / 60);
timer.m = checkTime(timer.m);
timer.timed -= timer.m * 1000 * 60;
timer.s = Math.floor(timer.timed / 1000);
timer.timed -= timer.s * 1000;
timer.s = checkTime(timer.s);
$time.html("" + timer.h + ":" + timer.m + ":" + timer.s);
//var t = setTimeout(time(timer), 10);
}else{
timer.current = new Date();
timer.pauseTime = timer.current - timer.paused;
timer.pauseTime += timer.pauseTimeBuffer;
//var t = setTimeout(time(timer), 10);
}
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
function init(timer){
var name = "#timer" + timer.id;
var $time = $('' + name)
$time.html("" + timer.h + ":" + timer.m + ":" + timer.s);
run();
}
function run(){
for(i = 0; i < timers.length;i++){
var timer = timers[i];
setTimeout(time(timer), 10);
}
setTimeout(run, 10);
}
function action(id, action){
if(action === "start"){
var t = timers[id - 1];
startTime(t);
}else if(action === "stop"){
var t = timers[id - 1];
stopTime(t);
}else if(action === "save"){
var t = timers[id - 1];
save(t);
}
}
function stopAll(){
for(i = 0; i < timers.length; i++){
var t = timers[i];
stopTime(t);
}
}
function add(){
stopAll();
var number = timers.length + 1;
var starttext = '"start"';
var savetext = '"save"';
var stoptext = '"stop"';
var newTimer = new timer(number);
timers.push(newTimer);
$('#timers').append("<br/>" +
"<h1>Timer " + number + "</h1>" +
"<div id=" + 'timer' + number + ">Test</div>" +
"<button onclick='action(" + number + ", " + starttext + ")" + "'>Start</button>" +
"<button onclick='action(" + number + ", " + stoptext + ")" + "'>Stop</button>" +
"<button onclick='add()'>Add</button>" +
"<button onclick='action(" + number + ", " + savetext + ")" + "'>Save</button>" +
"<p class='description' id='" + 'desc' + number + "'>Click here to enter a description</p>");
$(".description").click(function(){
var text = prompt("Please enter your description here");
if(text === ""||text === null) {
$(this).html("Click here to enter a description");
}else{
$(this).html(text);
timers[number - 1].desc = text;
}
});
init(newTimer);
setTimeout(startTime(newTimer));
}
Save is the function that I have problems with.
You cannot make client side Javascript and server side Javascript coexist at the same file. Jquery/HTML code runs inside a browser and nodejs/express runs inside a server.
Reference to Client-Server concept
https://softwareengineering.stackexchange.com/questions/171203/what-are-the-differences-between-server-side-and-client-side-programming
Some good reference to work with NodeJS
calling a server side function from client side(html button onclick) in node.js
Sample app
https://github.com/jmhdez/Nodejs-Sample
I am using Moment.js to track the duration of an action in my app. Currently, I have the following code:
var startMoment = null;
var actionClock = null;
function startClock() {
actionClock = setInterval(function(){
if (startMoment === null) {
startMoment = moment();
$('#duration').text('00:00:00');
} else {
var now = moment();
var span = moment.duration(now - startMoment);
$('#duration').text(span.minutes() + ':' + span.seconds() + '.' + span.milliseconds());
}
}, 1000);
}
function stopClock() {
clearInterval(actionClock);
var now = moment();
var span = moment.duration(now - startMoment);
$('#duration').text(span.minutes() + ':' + span.seconds() + '.' + span.milliseconds());
startMoment = null;
actionClock = null;
}
My problem is, the format of duration is awkward. I want to display the duration as mm:ss.lll. In other words, always show two digits for the minutes, two digits for the seconds, and three digits for the milliseconds. Currently, I see durations printed like 1:2.45. How do I format a duration created with Moment.js? If this is not possible, is there another library I should be using to track a duration and display it?
Thank you!
One way of doing this might be to convert your duration back into a moment (perhaps using milliseconds), and then using the moment's formatting.
moment.utc(span.asMilliseconds()).format('mm:ss.SSS');
var startMoment = null,
$durForm = $('#durationFormatted');
var actionClock = null;
function startClock() {
actionClock = setInterval(function() {
if (startMoment === null) {
startMoment = moment();
$('#duration').text('00:00:00');
$durForm.text('00:00.000');
} else {
var now = moment();
var span = moment.duration(now - startMoment);
$('#duration').text(span.minutes() + ':' + span.seconds() + '.' + span.milliseconds());
$durForm.text(moment(span.asMilliseconds()).format('mm:ss.SSS'));
}
}, 1000);
}
function stopClock() {
clearInterval(actionClock);
var now = moment();
var span = moment.duration(now - startMoment);
$('#duration').text(span.minutes() + ':' + span.seconds() + '.' + span.milliseconds());
$durForm.text(moment(span.asMilliseconds()).format('mm:ss.SSS'));
startMoment = null;
actionClock = null;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>
<div>Duration (original): <span id='duration'></span>
</div>
<div>Formatted moment: <span id='durationFormatted'></span>
</div>
<button onClick='startClock()'>Start Clock</button>
<button onClick='stopClock()'>Stop Clock</button>
I had a similar issue in my project and thankfully, Lodash was already a dependency. I was able to use the _.padStart method to get there.
let yourHours = _.padStart(span.hours().toString(),2,'0');
let yourMinute = _.padStart(span.minutes().toString(),2,'0');
let yourSeconds = _.padStart(span.seconds().toString(),2,'0');
I'm trying to get server time at start and update it, cause i've to cotnrol some elements with real time. The problem is that if my serverTime doesn't have T the time is NaN on firefox and IE, but if i replace the empty space with T on chrome and IE i've a wrong time.
I now the work-around of replacing white space with T sucks but im outta of time :)
Thanks everybody
At start:
$tmpTime = date("Y-m-d H:i:s");
Head:
<script>
var serverTime = '<?=$tmpTime?>';
serverTime = serverTime.replace(" ", "T");
</script>
Script:
setInterval(function () {
console.log(serverTime);
var tmpTime = new Date(serverTime);
console.log(tmpTime);
var t = tmpTime.getTime();
t = t + 1000;
tmpTime = new Date(t);
serverTime = t;
if (tmpTime.getMinutes() < 10) {
var minutes = "0" + tmpTime.getMinutes();
} else {
var minutes = tmpTime.getMinutes();
};
newTime = tmpTime.getHours() + ":" + minutes;
$('#liveTime').text(newTime);
if ($("#program li[time-id='" + newTime + "'][class='alert']").length !== 0) {
alert("Lo streaming da te programmato sta per iniziare!");
$("#program li[time-id='" + newTime + "'][class='alert']").removeClass("alert");
}
titleToShow();
}, 1000);
function titleToShow() {
$("#program li").each(function () {
var prevTime = $(this).prev("li").attr("time-id");
var thisTime = $(this).attr("time-id");
var nextTime = $(this).next("li").attr("time-id");
currentTime = Date.parse('01/01/2011 ' + newTime);
prevTime = Date.parse('01/01/2011 ' + prevTime);
nextTime = Date.parse('01/01/2011 ' + nextTime);
thisTimeNew = Date.parse('01/01/2011 ' + thisTime);
if (currentTime >= thisTimeNew && currentTime < nextTime && currentTime > prevTime) {
title = $(this).find("p").text();
if (title != $("p#playingTitle").text()) {
$("p#playingTitle").text(title);
}
}
})
}
Don’t use a formated date, just pass the Unix timestamp value to the script (don’t forget to multiply it by 1000, because JS works with milliseconds).
var serverTime = <?php echo time(); ?>;
var tmpTime = new Date(serverTime * 1000);
Need that, the counter should be start after button click, when start count up - start button must be inactive, after count up finish - button must be active and have someone function.
var refDate = new Date("2013 01 18 16:41");
var prepend = "This is a message ";
var append = new Date(refDate).toLocaleString();
var refValue = "1,100.00";
function insertCommas(nAmt) {
var currAmt = nAmt.toFixed(2);
while (/(\d+)(\d{3})/.test(currAmt)) {
currAmt = currAmt.replace(/(\d+)(\d{3})/, "$1,$2");
}
return currAmt;
}
function dispCounter() {
var currDate = new Date();
var elapsedSeconds = Math.round((refDate - currDate) / 100);
var elapsedValue = elapsedSeconds / 100;
var nRef = refValue.replace(/\,/g, "");
var result = insertCommas(nRef - elapsedValue);
document.getElementById('upCount').innerHTML = prepend + " $" + result + " since " + append;
setTimeout("dispCounter()", 1500);
}
navigator.appName == "Microsoft Internet Explorer" ? attachEvent('onload', dispCounter, false) : addEventListener('load', dispCounter, false);