How to Write the javascript Function in Asp.net MVC aspx View - javascript

Hi is there anyone who can help me with the following. I am having asp.net mvc aspx page ,i want to write javascript function but i am stuck as how i call that function ....
My function of javascript is
<script type="text/javascript">
function toTimeString(d) {
d = parse(d);
var h = d.getHours();
var s = "AM";
if (h > 12) {
h = h - 12;
s = "PM";
}
var m = d.getMinutes();
if (m < 10) {
m = "0" + m;
} else {
m = m + "";
if (m.length == 1) {
m = m + "0";
}
}
return h + ":" + m + " " + s;
}
function parse(v) {
if (!v)
return null;
if (!(v.constructor == String))
return v;
if (/^\/date\([\-0-9]+\)\//gi.test(v)) {
v = new Date(parseInt(v.substr(6), 10));
} else {
if (/^\/dateiso/gi.test(v)) {
v = v.substr(9);
v = v.substr(0, v.length - 1);
var tokens = v.split('T');
var date = tokens[0];
var time = tokens[1];
date = date.split('-');
time = time.split(':');
var d = new Date(date[0], parseInt(date[1]) - 1, date[2], time[0], time[1], parseFloat(time[2]));
d = new Date(d.getTime() + AtomDate.zoneOffset);
return d;
} else {
v = Date.parse(v);
}
}
return v;
}
</script>
and i am tried to call in the html like
<span style="font-size: 23px"><%= c.StartDate != null ? toTimeString(c.StartDate.Value): ""%></span>
but i am not being able to call toTimeString ,Please Help me Out

to init this function use:
<span style="font-size: 23px">
<script type="text\javascript">
<%= c.StartDate != null ? toTimeString(c.StartDate.Value): ""%>
</script>
</span>
you need to understand that when the page is rendered the javascript is just placed on the page that being sent to client, look at this as a cake recipe that is ready to pass over to someone else to use it.
the real sheaf (still using the analogy) is the browser that gets the recipe and follow the instruction and that's why you need to wrap you'r javascript with <script type="text\javascript">

Related

Filemaker: webviewer timer

I’m trying to make in FileMaker a web viewer to show some “countdown” for my medical office.
I’m trying to adapt this code I have found on internet:
"data:text/html,<html>
<head>
<script type='text/javascript'>
/*Setting JavaScript Variables to value of FileMaker fields*/
var targetTimeTxt = '" & Timer::Timestamp_End & "';
var status = '" & Timer::Status & "';
var labelTxt = '" & Timer::Label & "';
/*End FileMaker Fields*/
var currentTime = new Date();
var targetTime = new Date(targetTimeTxt);
var remaining = Math.floor((targetTime - currentTime)/1000);
function setClock()
{
var currentTime = new Date();
var clock = document.getElementById('clock');
var labelobj = document.getElementById('label1');
var secondsRemaining=0;
if(labelTxt=='')
{
labelobj.innerHTML='Timer';
}
else
{
labelobj.innerHTML=labelTxt;
}
if (targetTime>currentTime)
{
secondsRemaining=Math.floor((targetTime - currentTime)/1000);
}
var hours = Math.floor( secondsRemaining / 3600 );
var minutes = Math.floor((secondsRemaining%3600) / 60 );
if(minutes<10)minutes='0' + minutes;
var seconds = secondsRemaining%60;
if(seconds<10)seconds='0'+seconds;
clock.innerHTML=hours + ':' + minutes + ':' + seconds;
if(targetTimeTxt=='' || status=='Acknowledged' || ( secondsRemaining==0 && Math.floor(currentTime/1000)%2==0 ) )
{
document.body.style.backgroundColor='#FFFFFF';
if ( targetTimeTxt=='' || status=='Acknowledged' )
{
clock.innerHTML='--:--:--';
}
}
else if(secondsRemaining==0)
{
document.body.style.backgroundColor='#FFFF00';
document.getElementById('sound1').Play();
}
setTimeout('setClock();',1000);
}
</script>
</head>
<body style='margin:4px;padding:0;font-size:14px;font-weight:bold;font-family: Arial, Helvetica, sans-serif;text-align:center;background-color:#FFFFFF;' onload='setClock();'>
<div id='label1' style='font-size:10px;font-weight:bold;'>
</div>
<div id='clock'>
</div>
<embed src='file:///System/Library/Sounds/Glass.aiff' autostart='false' id='sound1'
enablejavascript='true' width='0' height='0'>
</body></html>"
The FileMaker Var are correct, and the time stamp end car get dd/mm/yyyy hh:mm:ss results.
The web viewer works, but the timer starts always with a 2640:mm:ss….. indeed of the duration time.
I suspect there is an error in the calculation of the code, but I have no idea where to look.
Can someone help me?
I hanno no idea of Java programming.
Thanks.
Here is something very simple you could use as your starting point:
Let ([
seconds = Timer::Timestamp_End - Get(CurrentTimestamp) ;
html = "data:text/html, <html>
<head>
<script type='text/javascript' language='javascript'>
function count_down(seconds) {
i = seconds;
h = Math.floor(i/3600);
m = Math.floor(i%3600/60);
s = i%60;
if (m < 10) { m = '0' + m };
if (s < 10) { s = '0' + s };
if (i > 0) {
document.getElementById('hr').innerHTML = h;
document.getElementById('min').innerHTML = m;
document.getElementById('sec').innerHTML = s;
i--;
setTimeout('count_down(i)', 1000);
}
else {
document.getElementById('timer').innerHTML = 'Expired';
}
}
</script>
</head>
<body onload='count_down(«seconds»)'>
<div id='timer'><span id='hr'></span>:<span id='min'></span>:<span id='sec'></span></div>
</body>
</html>"
] ;
Substitute ( html ; "«seconds»" ; GetAsNumber ( seconds ) )
)
This assumes the Timestamp_End field is a Timestamp field.

12 hour clock not displaying, but 24 hour clock displaying fine

I have this code so that when I click the buttons, it switches between the 12 hours clock and 24 hours clock.
The 24 hour clock displayed, but when I click the 12 hour clock button, nothing happens.
Google Inspect also says nothing. Any help would be appreciated.
function twelvehour() {
var dat = new Date();
var h = dat.getHours()
if (h >= 13) {
var h = dat.getHours() - 12
} else {
var h = dat.getHours()
}
var m = dat.getMinutes()
var s = dat.getSeconds()
if (h >= 12) {
document.getElementById("clock").innerHTML = h + ":" + m + ":" + s + "pm"
} else {
document.getElementById("clock").innerHTML = h + ":" + m + ":" + s
}
}
function tfourhour() {
var dat1 = new Date();
var h1 = dat1.getHours()
var m1 = dat1.getMinutes()
var s1 = dat1.getSeconds()
document.getElementById("clock").innerHTML = h1 + ":" + m1 + ":" + s1
}
setInterval(twelvehour, 1000);
setInterval(tfourhour, 1000);
document.getElementById("twelve").onclick = twelvehour()
document.getElementById("tfour").onclick = tfourhour()
<html>
<head>
<style>
button {
display: inline-block;
}
</style>
<title>Assignment 9c Clock</title>
</head>
<body>
<button type="button" style="width=500, height=500" id="twelve">12 Hour Clock</button>
<button type="button" style="width=500, height=500" id="tfour">24 Hour Clock</button>
<br>
<p id="clock"></p>
<script type="text/javascript" src="sample4.js">
</script>
</body>
</html>
You run two functions at the same time by calling setIterval twice.
twelvehour function doesn't work properly since you set h before it displayed.
Event handlers should be mapped with a function itself not a result of it.
And consider using a function that store the selected function.
let f = twelvehour;
f();
function twelvehour() {
var dat = new Date();
dat.setHours(14); // for test
var h = dat.getHours()
var m = dat.getMinutes()
var s = dat.getSeconds()
if (h >= 12) {
document.getElementById("clock").innerHTML = (h - 12) + ":" + m + ":" + s + "pm"
} else {
document.getElementById("clock").innerHTML = h + ":" + m + ":" + s
}
}
function tfourhour() {
var dat1 = new Date();
dat1.setHours(14); // for test
var h1 = dat1.getHours()
var m1 = dat1.getMinutes()
var s1 = dat1.getSeconds()
document.getElementById("clock").innerHTML = h1 + ":" + m1 + ":" + s1
}
setInterval(() => f(), 1000);
document.getElementById("twelve").onclick = () => { f = twelvehour; f(); }
document.getElementById("tfour").onclick = () => { f = tfourhour; f(); }
<html>
<head>
<style>
button {
display: inline-block;
}
</style>
<title>Assignment 9c Clock</title>
</head>
<body>
<button type="button" style="width=500, height=500" id="twelve">12 Hour Clock</button>
<button type="button" style="width=500, height=500" id="tfour">24 Hour Clock</button>
<br>
<p id="clock"></p>
</script>
</body>
</html>
Your main issue here is assigning onclick in a wrong way. You should drop the parentheses:
document.getElementById("twelve").onclick = twelvehour
Or, put it in the HTML:
<button type="button"
style="width: 500px; height: 500px;"
id="twelve"
onclick="twelvehour()">12 Hour Clock</button>
Here's how I would do it:
function Clock(displayFunc, twelveHour = true, interval = 1000){
let clock;
this.twelveHour = twelveHour; this.interval = interval;
this.start = ()=>{
const fun = ()=>{
let d = new Date, h = d.getHours(), m = d.getMinutes(), s = d.getSeconds(), z = d.getMilliseconds(), p = false;
if(this.twelveHour){
if(h > 12){
h -= 12; p = 'pm';
}
else{
p = 'am';
}
}
else if(h < 10){
h = '0'+h;
}
if(m < 10)m = '0'+m;
if(s < 10)s = '0'+s;
if(z < 10){
z = '00'+z;
}
else if(z < 99){
z = '0'+z;
}
displayFunc({hours:h.toString(), minutes:m.toString(), seconds:s.toString(), am_pm:p});
}
fun(); clock = setInterval(fun, this.interval);
return this;
}
this.stop = ()=>{
clearInterval(clock); clock = undefined;
return this;
}
}
let doc, bod, I; // for use on other loads
addEventListener('load', ()=>{
doc = document; bod = doc.body; I = id=>doc.getElementById(id);
const digital = I('digital'), clock = new Clock(o=>{
digital.textContent = o.hours+':'+o.minutes+':'+o.seconds+' '+o.am_pm;
});
clock.start();
}); // end load
<div id='digital'></div>

Javascript app freezing after approximately two hours (memory leak?)

I'm currently developing a home automation user interface, running on a wall-mounted android (version 4.2.2) tablet, which, after a couple of minutes of inactivity, displays a "screensaver" html page.
As you can see in the screenshot above, this "screensaver" basically consists of the following features :
a clock displaying the current time and date, triggered by the script date_time.js and refreshed at one second interval;
a picture on the top right-hand side which shows the current status of the alarm;
a picture "Touchez l'écran pour quitter le mode veille" which is randomly repositioned every 3500 miliseconds.
Both points 2) and 3) above are run by another script stored in a script called "screensaver_run.js". The method getAlarmDataFromDatabase is retrieving data from my mysql database.
Now, for the problem statement: after approximately two hours, the whole screen freezes (both the clock and the repositioning script) in such a way that even the tablet is no longer pingable. I suspect that a memory leak is occurring but after a couple of sleepless nights ... and a lot of coffee ... I am not able to find out the root cause of my issue.
Reading some documentation on the internet, notably https://www.lambdatest.com/blog/eradicating-memory-leaks-in-javascript, I have already implemented some changes such as changing the declaration of the variables from "var" to "let".
In Chrome, I run the script during 2 1/2 minutes and profiled the memory usage (I have the heaptimeline file available, if it can be of any help, but here I'm not quite sure how to analyse it?):
Besides, I queried the console for :
performance.memory.usedJSHeapSize and got some changing values :
3430886, 3195206, 4743246, 3402767, etc
performance.memory.jsHeapSizeLimit and got : 4294705152
Does anyone have any hint where to start investigating, knowing that debugging possibilities of this tablet are not as advanced as on a modern browser? My tablet is "already" 5 years old... Upgrading this tablet is not an option.
Many thanks for your time reading me and I do hope that my post is understandable, well documented and in the future, could help other to have restful nights :)
The code of my html page (named after 'screen_saver.html) is the following :
<!DOCTYPE html>
<html>
<head>
<title>Domoos | Screen saver screen</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"/>
<meta http-equiv="pragma" content="no-cache">
<link rel="shortcut icon" href="favicon.ico">
<link rel="stylesheet" type="text/css" href="css/mystyle_saver.css?rnd=999" />
<script type="text/javascript" src="scripts/date_time.js"></script>
<script type="text/javascript" src="scripts/screensaver_run.js"></script>
</head>
<body onload="runScreenSaver(); setup();">
<div style="position:absolute" id="randomPlacement">
<p><img src="assets/pictures/texte_sortie_veille.png" alt ="" style="width:90px;height:90px;" border="0"></p>
</div>
<div id="svg">
<svg height="210" width="1020">
<line x1="11" y1="100" x2="1015" y2="100" style="stroke:rgb(69,69,66);stroke-width:3" />
</svg>
</div>
<div id="date"></div>
<div id="time"></div>
<div id="icon_alarm">
<img id="img_alarm" src="assets/icons/alarme_eteinte.png" alt ="" style="width:27px;height:35px;">
</div>
<div id="tag_temperature">
<p>21°C</p>
</div>
<div id="tag_free_text">
<p>151<sup>ème</sup> jour de l'année 2020.<br>Bonsoir</p>
</div>
<div id="meteo_icon">
<img src="assets/meteo_icons/eclaircies-big.png" alt="" style="width:40px;height:40px;">
</div>
<div id="tag_weather_condition">
<p>Eclaircies</p>
</div>
</body>
</html>
Code of my javasript file screensaver_run.js:
function runScreenSaver()
{
let xmin = 0;
let xmax = 890;
let ymin = 0;
let ymax = 430;
let sDate;
let sTime;
let bOverlapAuthorised;
let bDisplayPos;
let zRandomImage;
let xCoord;
let yCoord;
let xCoordStr;
let yCoordStr;
bOverlapAuthorised = true;
bDisplayPos = false;
// If overlap is forbidden, the x min and y min parameters will be redefined to be slightly below the line
if (!bOverlapAuthorised)
{
xmin = 15;
ymin = 130;
}
// Computes a random x and y, based on the min and ma
xCoord = Math.floor((Math.random()*xmax)+xmin);
yCoord = Math.floor((Math.random()*ymax)+ymin);
xCoordStr = xCoord.toString() + "px";
yCoordStr = yCoord.toString() + "px";
zRandomImage = document.getElementById("randomPlacement");
zRandomImage.style.left = xCoordStr;
zRandomImage.style.top = yCoordStr;
// Instead of displaying a message in the 'tag_free_text',
// shows the randomly defined coordinates of the 'randomPlacement' object
if (bDisplayPos)
{
document.getElementById("tag_free_text").innerHTML = 'X:' + xCoordStr + '<br>Y:' + yCoordStr;
}
document.getElementById("date").innerhtml=getTimeDate('date');
getAlarmDataFromDatabase();
zRandomImage = null;
xCoord = null;
yCoord = null;
xCoordStr = null;
yCoordStr = null;
setTimeout('runScreenSaver()','3500');
}
function setup()
{
this.addEventListener("mousemove", exitScreenSaver, false);
this.addEventListener("mousedown", exitScreenSaver, false);
this.addEventListener("keypress", exitScreenSaver, false);
this.addEventListener("DOMMouseScroll", exitScreenSaver, false);
this.addEventListener("mousewheel", exitScreenSaver, false);
this.addEventListener("touchstart", exitScreenSaver, false);
this.addEventListener("MSPointerMove", exitScreenSaver, false);
}
function getAlarmDataFromDatabase()
{
let ajax = new XMLHttpRequest();
let id_component;
let technical_name_html;
let comp_value;
let data;
ajax.open("GET", "php/data4screensaver1.php", true);
ajax.send();
ajax.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
data = JSON.parse(this.responseText);
for(var a = 0; a < data.length; a++)
{
id_component = data[a]['id_component'];
technical_name_html = data[a]['technical_name_html'];
comp_value = parseInt(data[a]['value']);
}
data = null;
console.log("ID Component: " + id_component);
//console.log("Valeur de l'alarme : " + comp_value);
switch (comp_value)
{
case 0:
case 50:
case 100:
displayPictureAlarm(comp_value);
break;
default:
displayPictureAlarm(-1);
break;
}
}
};
ajax = null;
id_component = null;
technical_name_html = null;
comp_value = null;
}
function exitScreenSaver(e)
{
goActive(e);
}
function goActive(event)
{
// do something
console.log(".. active ..");
//event.preventDefault();
this.removeEventListener("mousemove", exitScreenSaver);
this.removeEventListener("mousedown", exitScreenSaver);
this.removeEventListener("keypress", exitScreenSaver);
this.removeEventListener("DOMMouseScroll", exitScreenSaver);
this.removeEventListener("mousewheel", exitScreenSaver);
this.removeEventListener("touchstart", exitScreenSaver);
this.removeEventListener("MSPointerMove", exitScreenSaver);
window.open("index.html","_self");
}
function displayPictureAlarm(pValue)
{
let z;
z = document.getElementById("img_alarm");
if (pValue == 0) // désarmée
{
z.src = "assets/icons/alarme_desarmee.png";
}
if (pValue == 50) // partielle
{
z.src = "assets/icons/alarme_partielle.png";
}
if (pValue == 100) // totale
{
z.src = "assets/icons/alarme_totale.png";
}
if (pValue == -1) // éteinte
{
z.src = "assets/icons/alarme_eteinte.png";
}
z = null;
}
Code of my javascript file datetime.js (as called in the the method runScreenSaver above):
function getDate(id)
{
date = new Date;
year = date.getFullYear();
month = date.getMonth();
month += 1;
d = date.getDate();
day = date.getDay();
days = new Array('Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi');
if (d<10)
{
d = "0"+d;
}
if(month<10)
{
month = "0"+month;
}
result = ''+days[day]+' '+d+'.'+month+'.'+year;
result = days[day]+' '+d+'.'+month+'.'+year;
document.getElementById(id).innerHTML = result;
setTimeout('getDate("'+id+'");','1000');
return true;
}
function getTimeDateMainScreen()
{
var za;
var zb;
var zc;
var mydate;
var result1;
var result2;
var result3;
mydate = new Date;
year = mydate.getFullYear();
month = mydate.getMonth();
day = mydate.getDate();
weekday = mydate.getDay();
hrs = mydate.getHours();
mns = mydate.getMinutes();
secs = mydate.getSeconds();
days = new Array('Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi');
month += 1;
if (day < 10)
{
day = "0" + day;
}
if(month < 10)
{
month = "0" + month;
}
if(hrs < 10)
{
hrs = "0" + hrs;
}
if(mns < 10)
{
mns = "0" + mns;
}
if(secs < 10)
{
secs = "0" + secs;
}
//result = ''+days[weekday]+' '+d+'.'+month+'.'+year;
//result = days[weekday]+' '+d+'.'+month+'.'+year;
result1 = day + "." + month + "." + year;
result2 = days[weekday];
result3 = hrs + ":" + mns + ":" + secs;
za = document.getElementById("curr_date");
zb = document.getElementById("curr_weekday");
zc = document.getElementById("curr_time");
za.innerHTML = result1;
zb.innerHTML = result2;
zc.innerHTML = result3;
za = null;
zb = null;
zc = null;
mydate = null;
result1 = null;
result2 = null;
result3 = null;
setTimeout('getTimeDateMainScreen();','500');
}
function getTime(id)
{
date = new Date;
h = date.getHours();
if(h<10)
{
h = "0"+h;
}
m = date.getMinutes();
if(m<10)
{
m = "0"+m;
}
s = date.getSeconds();
if(s<10)
{
s = "0"+s;
}
result = ''+h+':'+m+':'+s;
document.getElementById(id).innerHTML = result;
setTimeout('getTime("'+id+'");','1000');
return true;
}
function getTime2()
{
date = new Date;
h = date.getHours();
if(h<10)
{
h = "0"+h;
}
m = date.getMinutes();
if(m<10)
{
m = "0"+m;
}
s = date.getSeconds();
if(s<10)
{
s = "0"+s;
}
result = ''+h+':'+m+':'+s;
document.getElementById("time").innerHTML = result;
setTimeout('getTime2();','1000');
}
function getTimeDate(id)
{
let date;
let year;
let month;
let d;
let day;
let days;
let h;
let m;
let s;
let result;
date = new Date;
console.log("J'affiche la date3");
year = date.getFullYear();
month = date.getMonth();
month += 1;
d = date.getDate();
day = date.getDay();
days = new Array('Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi');
h = date.getHours();
m = date.getMinutes();
s = date.getSeconds();
if (d<10)
{
d = "0"+d;
}
if(month<10)
{
month = "0"+month;
}
if(h<10)
{
h = "0"+h;
}
if(m<10)
{
m = "0"+m;
}
if(s<10)
{
s = "0"+s;
}
result = ''+days[day]+' '+d+'.'+month+'.'+year +' ' + h+':'+m+':'+s;
document.getElementById(id).innerHTML = result;
date = null;
year = null;
month = null;
d = null;
day = null;
days = null;
h = null;
m = null;
s = null;
result = null;
setTimeout('getTimeDate("'+id+'");','1000');
return true;
}
And, finally, here is my php (data4screensaver1.php) to retrieve the data from my mysql database :
<?php
$host = "ip_Address_db";
$db_user_encoded = "user_encoded";
$db_password_encoded = "pw_encoded";
$db_name_encoded = "db_name_encoded";
$conn = mysqli_connect($host, (encrypt_decrypt('decrypt', $db_user_encoded)), (encrypt_decrypt('decrypt', $db_password_encoded)), (encrypt_decrypt('decrypt', $db_name_encoded )));
$result = mysqli_query($conn, "CALL sp_tbl_domotique_components_get_lab61()");
$data = array();
while ($row = mysqli_fetch_object($result))
{
array_push($data, $row);
}
echo json_encode($data);
exit();
function encrypt_decrypt($action, $string)
{
$output = false;
$encrypt_method = "AES-256-CBC";
$secret_key = '$SecretKey$';
$secret_iv = '$SecretIV$';
// hash
$key = hash('sha256', $secret_key);
// iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
$iv = substr(hash('sha256', $secret_iv), 0, 16);
if ( $action == 'encrypt' ) {
$output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
$output = base64_encode($output);
} else if( $action == 'decrypt' ) {
$output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
}
return $output;
}
?>

Browser Bug showing time text on input

I am dealing with the following puzzle and I cannot understand why it is happening.
I have the following [I believe to be] equivalent pieces of javascript code, but one does not work as expected (notice the Console.Log):
Updates the UI a single time, then unexpectantly stops updating : http://jsfiddle.net/silentwarrior/1m0v6oj1/
jQuery(function () {
var isWorking = true;
if (isWorking) {
var timeEnd = 1431220406000; // generated from php
var timeNow = 1431210557000; // generated from php
var counter = 1;
var t = "";
setInterval(function () {
try {
var c = timeEnd - timeNow - counter;
console.log(c);
var d = new Date(c);
if (c <= 1) {
window.location.href = window.location.href;
return;
}
t = "";
if (d.getHours() > 0) {
t += d.getHours() + "h ";
}
if (d.getMinutes() > 0) {
t += d.getMinutes() + "m ";
}
t += d.getSeconds();
jQuery("#factory_start_prod").val("Working ... " + t + "s left");
counter = counter + 1;
} catch (e) {
}
}, 1000);
}
});
Updates the UI constantly as expected: http://jsfiddle.net/silentwarrior/n3gkum2e/
jQuery(function () {
var isWorking = true;
if (isWorking) {
var timeEnd = 1431220406000;
var timeNow = 1431210557000;
var counter = 1;
var t = "";
setInterval(function () {
try {
var c = timeEnd - Date.now();
console.log(c);
var d = new Date(c);
if (c <= 1) {
window.location.href = window.location.href;
return;
}
t = "";
if (d.getHours() > 0) {
t += d.getHours() + "h ";
}
if (d.getMinutes() > 0) {
t += d.getMinutes() + "m ";
}
t += d.getSeconds();
jQuery("#factory_start_prod").val("Working ... " + t + "s left");
counter = counter + 1;
} catch (e) {
}
}, 1000);
}
});
The only difference from each other is that, the one that works uses Date.now() to get the current timestamp, while the other one uses a pre-built time stamp.
Why would one example update the text in the input correctly while the other wouldn't?
PS: it is important to me to use generated timestamps instead of Date.now() in order to not depend on the users system when calculating the time left.
Your first example is working, however with each iteration you are only subtracting 1 from the timestamp value, which is equivalent to 1ms. Hence the value never appears to change unless you wait a really long time. You need to increment the counter by 1000 on each iteration for a second to be counted:
counter = counter + 1000;
Updated fiddle

Javascript: Grab an array and sum all values

In my project, users can add timecode in and out points for their project, and the project automatically figures out the total duration of the timecode. But I want to add a function that will take all the available timecode durations, convert them to seconds, add them together, then convert the final number back to timecode and put it in a text input.
This is my code, but I keep getting syntax errors:
function timeToSeconds(t) {
var tc = t.split(':');
return parseInt(tc[0])*3600 + parseInt(tc[1])*60 + parseInt(tc[2]);
}
function tcDuration(tcin, tcout) {
function z(n){return (n<10?'0':'') + n;}
var duration = timeToSeconds(tcout) - timeToSeconds(tcin);
var hoursmins = Math.floor(duration / 60);
return z(Math.floor(hoursmins/60)) + ':' + z(hoursmins % 60) + ':' + z(duration % 60);
}
// Run this function every time a film_tc_out cell is changed
function film_tc_Duration() {
if (document.getElementById("film_tc_in").value == '') {var film_tc_in = '00:00:00';} else { var film_tc_in = document.getElementById("film_tc_in").value;}
if (document.getElementById("film_tc_out").value == '') {var film_tc_out = '00:00:00';} else { var film_tc_out = document.getElementById("film_tc_out").value;}
document.getElementById("film_tc_duration").value = tcDuration(film_tc_in, film_tc_out);
}
// Run this function every time a src_tc_out cell is changed
function src_tc_Duration() {
if (document.getElementById("src_tc_in").value == '') {var src_tc_in = '00:00:00';} else { var src_tc_in = document.getElementById("src_tc_in").value;}
if (document.getElementById("src_tc_out").value == '') {var src_tc_out = '00:00:00';} else { var src_tc_out = document.getElementById("src_tc_out").value;}
document.getElementById("src_tc_duration").value = tcDuration(src_tc_in, src_tc_out);
}
// Run this function every time a src_wd_out cell is changed
function src_wd_Duration() {
if (document.getElementById("src_wd_in").value == '') {var src_wd_in = '00:00:00';} else { var src_wd_in = document.getElementById("src_wd_in").value;}
if (document.getElementById("src_wd_out").value == '') {var src_wd_out = '00:00:00';} else { var src_wd_out = document.getElementById("src_wd_out").value;}
document.getElementById("src_wd_duration").value = tcDuration(src_wd_in, src_wd_out);
}
function total_tc_Duration() {
var val = document.getElementsByClassName('.asset_src_tc_duration');
var total_tc = 0;
var v;
for (var i = 0; i < val.length; i++) {
v = timeToSeconds(val[i]);
if (!isNaN(v)) total_tc += v;
}
return (total_tc);
}
function updateAssetTimecode() {
document.getElementById("timecode_total").value = total_tc_Duration();
}
Update: I've rewritten the For Loop to see if that helps - it currently gives me an answer now, although the answer is always "0". It's not spitting out any errors but it seems to think the variable val isn't a number?
Your tcDuration function won't work like you expect. You don't subtract the already calculated hours before doing the minutes calculation and the same with seconds.
function tcDuration(tcin, tcout) {
function z(n){return (n<10?'0':'') + n;}
var duration = timeToSeconds(tcout) - timeToSeconds(tcin);
var hoursmins = Math.floor(duration / 60);
return z(Math.floor(hoursmins / 60)) + ":" + z(hoursmins % 60) + ":" + z(duration % 60);
}

Categories