Timer Using Javascript in mvc - javascript

Below are the controller and view of my application from controller m passing the difference of start time and end time in duration and I want to access this duration to view page so i can assign duration value to `javascript timer and start the clock I have done using viewbag but i m getting null value i m working on online examination and i want to start a timer like countdown time when user click on start
in it can anybody help I m creating a timer control by taking the difference between two times in mvc
public ActionResult ApplyForTest(int Test_Id)
{
EAssessmentNew.BAL.StudentBal stuBal = new EAssessmentNew.BAL.StudentBal();
ViewBag.TestId = Test_Id;
DataTable testSchedule = stuBal.getTestDateTime(Test_Id);
ViewBag.Sysdate = DateTime.Now.ToShortDateString();
ViewBag.SysTime = DateTime.Now.ToShortTimeString();
for (int i = 0; i < testSchedule.Rows.Count; i++)
{
Test Date_Time = new Test();
ViewBag.Test_Date = testSchedule.Rows[i]["Test_Date"].ToString();
ViewBag.Start_Time = testSchedule.Rows[i]["Start_Time"].ToString();
ViewBag.End_Time = testSchedule.Rows[i]["End_Time"].ToString();
DateTime strtTime = DateTime.Parse(ViewBag.Start_Time);
DateTime endTime = DateTime.Parse(ViewBag.End_Time);
TimeSpan duration = (endTime - strtTime);
ViewBag.a = duration;
}
return View();
}
#model List<EAssessmentNew.Models.Question>
#{
ViewBag.Title = "TestStarted";
Layout = "~/Views/StudentMaster.cshtml";
TimeSpan t = ViewBag.a;
}
<script src="~/Scripts/jquery.js"></script>
<script src="~/Scripts/jquery-1.5.1.js"></script>
<script type="text/javascript">
var myVar = setInterval(myTimer, 1000);
var d = '#ViewBag.duration';
alert(d);
var testDate = '#ViewBag.Test_Date';
var startTime = '#ViewBag.Start_Time';
var EndTime = '#ViewBag.End_Time';
d.setHours(00, d, 59, 00);
function myTimer() {
if (d.getSeconds() <= 1)
d.setMinutes(d.getMinutes() - 1, 59, 00);
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds() - 1;
if (m == 0 && s == 1)
window.location.href = "showresults.aspx";
document.getElementById("lblCtime").innerHTML = h + ":" + m + ":"s;
d.setMinutes(m, s);
//setInterval(myTimer, 1000);
}
</script>
Above mention are the controller and view of my application from controller m passing the difference of start time and end time in duration and i want to access this duration to view page so i can assign duration value to `javascript timer and start the clock i hv done using viewbag but i m getting null value i m working on online examination and i want to start a timer like countdown time when user click on start
in it can anybody help I m creating a timer control by taking the difference between two times in mvc
I have used all the required javascript but m getting null value on viewpage viewbag

I would seriously take a look at SignalR for this instead of doing this in javascript. You can have your timer run on the server tied to a particular web connection to the SignalR hub and then have the SignalR Hub broadcast to your javascript method the running clock.

Related

variables in a function not updating constantly when called on node side

I have a function called startTime() which gets the current time with h set to the hour and m set to minutes. The error with this code is after I exported my javaScript side function to node with the specific variables when I call back h and m their values don't get updated with the startTime function they are stuck to the values they first had when I run startTime in the javascript side. I tried to setInterval to keep on calling startTime every 500 milliseconds but that didn't fix it.function refreshStartTime() {setInterval(startTime, 500);} .I also tried debugging it with an alert on the HTML side which printed the correct/constantly updating values of h and m.```function testAlert(){alert(h + ":" + m)} .Do you have any idea why it's not updating on the node side or how to solve this issue? Thanks in advance.
JavaScript side
function startTime() {
var today = new Date();
globalThis.h = today.getHours();
m = today.getMinutes();
var s = today.getSeconds();
globalThis.m = checkTime(m);
s = checkTime(s);
var t = setTimeout(startTimeAudio, 500);
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
startTime()
module.exports = {
startTime,
h,
m,
};
Node side
const qw = require('./index.js');
const timeH = qw.h;
const timeM = qw.m;
Change your module.exports to
module.exports = {
startTime,
...globalThis
}

Javascript daily countdown only showing for WordPress admins, not public?

On our site we're trying to execute a script that counts down to midnight everyday, displays a message, and then "resets" at midnight.
The message is basically "Order within X1, Get By X2"
The script calculates X1 to be XX Hours XX Minutes until midnight. X2 is 5 days, after today (if today is the 1st, it would be the 2nd + 5 giving you the 7th, with the exception of Sunday, then it will automatically skip to the Monday immediately after).
The problem though is that for some reason this script refuses to load for the front-end user, yet as a logged in admin I can see the code.
<!-- Allows to add estimated delivery time to the product and/or cart page -->
<div class="dailytimer"><strong>Order within <span id='mycountdown' style="color: #FF0000;"></span>, Get it by <span id="delDate" style="color: #FF0000;"></span></strong></div>
<script>
// First part of output
var myreset = [00,00,00]; // at what time to reset - 19:40:00
// Added myCountDownDiv variable to prevent jquery from walking the DOM o every update
var myCountDownDiv = document.getElementById('mycountdown');
var mycountdown = startCountdown();
function startCountdown(){
var enddate = calculateEndDate();
return setInterval(function(){tickTock(calculateStartDate(),enddate)}, 1000);
}
function calculateStartDate(){ //this needs to be edited if using the server time
return new Date();
}
function calculateEndDate(){
var enddate = new Date();
enddate.setHours(myreset[0]);
enddate.setMinutes(myreset[1]);
enddate.setSeconds(myreset[2]);
return enddate;
}
function tickTock(startdate, enddate){
var diff = enddate.getTime() - startdate.getTime();
d = diff >= 0 ? diff : diff + 24*3600*1000;
var h = Math.floor(d / 3600 / 1000);
var m = Math.floor(d / 60 / 1000) - 60*h;
var s = Math.floor(d / 1000) - 3600*h - 60*m;
printCountdown(h,m,s);
}
function pluralize(word,count){
return (count > 1) ? word+'s ' : word+' ';
}
function printCountdown(h,m,s){
// Updated string concatination. 'and' was deisplayed after the seconds value
var t = h + pluralize(' hour',h)+ m+pluralize(' minute',m);
myCountDownDiv.innerText = t;
// Removed jquery
//$('#mycountdown').html(t);
}
var fromDate = new Date();
fromDate.setDate(fromDate.getDate() + 6);
if (fromDate.is().saturday() || fromDate.is().sunday()) {
fromDate = fromDate.next().monday();
}
document.getElementById('delDate').innerHTML = fromDate.toString('ddd MMMM dS');
</script>
It's using a date JS file I found online to calculate the dates. I'm also pretty sure there's a better way for us to "insert" the code into the page without literally coping it into a html widget inside of elementor (we're using it as a page builder) but I just haven't really thought of one off hand.
Any help would be greatly appreciated as I'm about 5 steps from wanting to just hit delete on the whole thing haha

How add PHP code to my countdown javascript code for add data to MySQL column automatically after countdown finished?

This is my countdown javascript code everyday on 23:00 of local time will finish and after 1 hour again will start to countdown for tomorrow and this continues. I wanted to know is it possible to add PHP code to this till after countdown finished everyday It adds "5" to my "Credit" column ("Credit" + 5 ) in my MySQL automatically ? appreciate for any kind of guidance.
<script>
var countDown = (function() {
var startStream;
var endStream;
var streamingText = 'Your match started!';
var updateElement;
// Pad single digit numbers
function pad(n) {
return (n<10?'0':'') + +n;
}
// Format a time difference as hh:mm:ss
// d0 and d1 are date objects, d0 < d1
function timeDiff(d0, d1) {
var diff = d1 - d0;
return pad(diff/3.6e6|0) + ':' + pad((diff%3.6e6)/6e4|0) + ':' + pad(diff%6e4/1000|0);
}
// start, end are UNIX UTC time values in seconds for the start and end of streaming
return function(elementId, start, end) {
var now = new Date();
var returnValue;
// By default, run again just after next full second
var delay = 1020 - now.getMilliseconds();
// turn start and end times into local Date objects
if (start) startStream = new Date(start*1000);
if (end) endStream = new Date(end*1000);
// If now is after endStream, add 1 day,
// Use UTC to avoid daylight saving adjustments
if (now > endStream) {
endStream.setUTCHours(endStream.getUTCHours() + 24);
startStream.setUTCHours(startStream.getUTCHours() + 24);
}
// Store the element to write the text to
if (elementId) updateElement = document.getElementById(elementId);
// If it's streaming time, return streaming text
if (now >= startStream && now < endStream) {
returnValue = streamingText;
// Run again after streaming end time
delay = endStream - now;
} else {
// Otherwise, count down to startStream
returnValue = timeDiff(now, startStream);
}
// Write the time left or streaming text
updateElement.innerHTML = returnValue;
// Call again when appropriate
setTimeout(countDown, delay);
};
}());
// Testing code
// Create dates for a local time of 21:00 today
var myStart = new Date();
myStart.setHours(23,0,0,0);
var myEnd = new Date()
myEnd.setHours(24,0,0,0);
// Create UNIX time values for same time as UTC
var startUTCTimeValue = myStart/1000|0
var endUTCTimeValue = myEnd/1000|0
// Run when page loads
window.onload = function() {
countDown('foo', startUTCTimeValue, endUTCTimeValue);
}
</script>
<font face="Trebuchet MS">
<div id="foo" style="color: white; font-size: 14px; font-weight: bold;"></div>
Jquery Ajax is the way to go here i guess.
It seems like you are very new and might not know what ajax is.
In short with Ajax you can call a webpage url in the background. So You could call www.yourdomain.com/addCredits.php
It will do the same as if you would visit that url in your browser. Just write your SQL Code inside that addCredits.php File and you're done.
Just add something like this to your javascript:
$.ajax({url: "addCredits.php"});
You will have to embed jquery inside your document first though.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
And also you might want to wait for that script to load before you call that function:
$( document ).ready(function() {
$.ajax({url: "addCredits.php"});
});
Edit:
Your Counter acutally seems to continue in a loop since it keeps up calling itself in the end.
But i would say just put it where your setTimeout is at the end of your function.
Edit2:
Here is an Example with a Clock, your code seems to be over-complicated to be honest. It doesn't really work when i put it in a fiddle aswell...
You could just use this instead:
function startTime() {
// set time variables h=hour, m=minute, s=second
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
//check if 0's have to be added for better appearance. no logical use!
m = checkTime(m);
s = checkTime(s);
//display current time on the element with id="txt"
document.getElementById('txt').innerHTML =
h + ":" + m + ":" + s;
//check if its 23:00:00 ... if so call addCredits.php
if(h == 23 && m == 00 && s == 00) {
$.ajax({url: "addCredits.php"});
}
//restart this function every second to update the clock
var t = setTimeout(startTime, 1000);
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>

Real Time decreasing value in php

I need some advice and logic in my problem.
So, I have an entrydate, from database, then the running current date, and a value of 10(double type in database). So, I know how to calculate the diff of the entrydate and current date, right. So I convert it to seconds then to a number(9.23165).
|Entry |Current Date|Diff(in number)|
|2:00:00 PM |2:30:00 PM | 5.00(Sample)|(First User)
So basically, as current date goes on, can PHP show the deduction on real time? Or I need to refresh? What I need is for it to display the deduction without refreshing. So basically, I need to know what I have to do. Maybe javascipt and ajax?
What you would need are a few Javascript/jQuery functions to update the browser in real time.
var myTimer;
var startTime;
function startTimer() {
stopTimer(); // Reset
startTime = new Date(); // Save to calculate difference
myTimer = setInterval(clockTicking, 1000);
}
function stopTimer() {
clearInterval(myTimer);
}
function clockTicking() {
var now = new Date();
var timeDiff = new Date(now - startTime); // constructor uses UTC, so use UTC date functions from here on
var hours = (timeDiff.getUTCHours() < 10) ? '0' + timeDiff.getUTCHours() : timeDiff.getUTCHours();
var mins = (timeDiff.getUTCMinutes() < 10) ? '0' + timeDiff.getUTCMinutes() : timeDiff.getUTCMinutes();
var secs = (timeDiff.getUTCSeconds() < 10) ? '0' + timeDiff.getUTCSeconds() : timeDiff.getUTCSeconds();
$("<element-where-you-display>").html(hours + ':' + mins + ':' + secs);
}
In Javascript you can call startTimer() to kick it off.

Create a countdown timer (that accounts for SetInterval/Timeout Google Chrome tab "error")

I created a countdown timer in Javascript; it was successful, expect not complete. In fact, mathematically, it is correct, but Google Chrome's browser settings "pause" (for lack of a better term) SetInterval/Timeout, which means that if a user of my countdown program switches between tabs on their browser, then the execution of the function will not occur exactly at the set time limit.
I need help implementing this basic time logic from W3Schools:
http://www.w3schools.com/js/tryit.asp?filename=tryjs_timing_clock
<!DOCTYPE html>
<html>
<head>
<script>
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
</script>
</head>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>
and this attempt to account for the browser SetInterval/Timeout interference: http://jsfiddle.net/7f6DX/31/
var div = $('div');
var a = 0;
var delay = (1000 / 30);
var now, before = new Date();
setInterval(function() {
now = new Date();
var elapsedTime = (now.getTime() - before.getTime());
if(elapsedTime > delay)
//Recover the motion lost while inactive.
a += Math.floor(elapsedTime/delay);
else
a++;
div.css("right", a);
before = new Date();
}, delay);
Thanks for any help that you can provide.
You should use real-world time to update your timer instead of relying on the accuracy of setInterval.
The w3schools example you gave does exactly this; every 500ms it grabs the current time, formats it, and updates the display. When the tab is inactive, this update may occur less frequently than 500ms (Chrome can slow it down to once every 1-2s), but nevertheless, when the update does occur, you will display correct information.
// countdown for 1 minute
countdown(60);
function countdown(seconds) {
// current timestamp.
var now = new Date().getTime();
// target timestamp; we will compute the remaining time
// relative to this date.
var target = new Date(now + seconds * 1000);
// update frequency; note, this is flexible, and when the tab is
// inactive, there are no guarantees that the countdown will update
// at this frequency.
var update = 500;
var int = setInterval(function () {
// current timestamp
var now = new Date();
// remaining time, in seconds
var remaining = (target - now) / 1000;
// if done, alert
if (remaining < 0) {
clearInterval(int);
return;
}
// format
var minutes = ~~(remaining / 60);
var seconds = ~~(remaining % 60);
// display
document.getElementById("countdown").innerHTML
= format(minutes) + ":" + format(seconds);
}, update);
}
function format(num) {
return num < 10 ? "0" + num : num;
}
<div id="countdown"></div>
Run this snippet and switch around to different tabs. Your countdown will be off by a maximum of 500ms (the update frequency).
For what it's worth, a similar idea can be applied to animations.
When designing an animation, you should have a formula for the position x as a function of time t. Your rendering clock (whether it is setInterval, setTimeout, or requestAnimationFrame) is not necessarily reliable, but your physics clock (real-world time) is. You should decouple the two.
Every time you need to render a frame, consult the physics clock for the time t, calculate the position x, and render that position. This is a really great blog post which goes into great detail on animations and physics, from which I borrowed the above idea.

Categories