Javascript: Grab an array and sum all values - javascript

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);
}

Related

Insert two scripts in the same <script> tag without conflicts

I have to put these two scripts in a single tag without them coming into conflict but I can not make it. Please, how can I do it?
Also is it better to insert multiple scripts in the same tag?
Script 1
var sec = 04;
var hour = 00;
var time0, time1;
var delay=0;
var duringtime = 1000;
time1 = (hour *10000 + min * 100 + parseInt(sec)).toString();
console.log("time1", time1);
function refresh() {
........
}
}
refresh();
Script 2
var min = 80;
var max = 85;
var random = Math.floor(Math.random() * (max - min)) + min;
if (localStorage.getItem("stockcount_99")) {
if (localStorage.getItem("stockcount_99") >= duration) {
var value = random;
} else {
var value = localStorage.getItem("stockcount_99");
}
} else {
var value = random;
}
document.getElementById('divCounter').innerHTML = value;
var stockcount_99 = function() {
if (value <= stopValue) { // end count down. <= or >=
clearInterval(interval);
value = stopValue;
} else {
value = parseInt(value) - 1; // + 1 or - 1
localStorage.setItem("stockcount_99", value);
}
document.getElementById('divCounter').innerHTML = value;
};
var interval = setInterval(function() {
stockcount_99();
}, speedcontrol);
With the following method can I isolate the two scripts and thus prevent any conflicts?
(function() {
...script 1...
})()
(function() {
...script 2...
})()

JavaScript - Delay execution of certain javascript

I need help in delaying the execution of my javascript.(not making the javascript to execute right after the webpage is being loaded) I wish to execute the javascript only after 10s after the webpage is being loaded. How can I do that? This is the script.
<script>
var interval = 10000;
var current_index = -1;
var sales_feeds = [];
var showtime = 5000;
<?php $s = get_option('wc_feed_delay_between_popups_appear');
if (!$s) {
$s = 5000;
}
?>
function hide_prev_feed_notify(index)
{
if( sales_feeds.eq(current_index).length > 0 )
{
sales_feeds.eq(current_index).animate({bottom: '-90px'}, 500);
}
}
function show_live_feed_notify(index)
{
sales_feeds.eq(index).animate({bottom: '10px'}, 1000);
current_index = index;
}
function show_next_live_notify()
{
if( (current_index + 1) >= sales_feeds.length )
{
current_index = -1;
}
//add randomness
current_index = (Math.floor(Math.random() * (sales_feeds.length + 1))) - 1;;
if( window.console )
console.log('will show ' + (current_index+1));
show_live_feed_notify(current_index + 1);
setTimeout(function() { hide_prev_feed_notify(current_index + 1); }, showtime);
}
function stop_live_notify()
{
removeInterval(inverval);
}
function readCookie(name)
{
var nameEQ = escape(name) + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++)
{
var c = ca[i];
while (c.charAt(0) === ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) === 0) return unescape(c.substring(nameEQ.length, c.length));
}
return null;
}
jQuery(function()
{
jQuery('.wc_feed_close_btn').click(function()
{
var days = 30;
var date = new Date();
date.setTime(date.getTime() + (days *24 *60 *60 *1000));
if(window.console)
console.log(date.toGMTString());
document.cookie = 'wc_feed_closed=true; expires=' + date.toGMTString() + ';';
jQuery('.live-sale-notify').css('display', 'none');
clearInterval(interval);
return false;
});
sales_feeds = jQuery('.live-sale-notify');
show_next_live_notify();
interval = setInterval(show_next_live_notify, (showtime + <?php print $s + 100; ?>));
});
</script>
Note: I want to delay the following execution.
function show_live_feed_notify(index)
{
sales_feeds.eq(index).animate({bottom: '10px'}, 1000);
current_index = index;
}
I tried inserting
var delay = 10000;
or
var interval = 10000;
none of them seem to work.
I also tried
setTimeout (function(); 3000);
it came out with uncaught syntax error.
Please Help me guys!
Note: I'm new to js/php coding...
Looking at your code, I think you should just remove the line
show_next_live_notify();
at the bottom of your script. It automatically executes everything right upon start instead of letting setInterval do its job
To delay the whole script, replace the last two lines in the jQuery call with something like this:
function startMe() {
interval = setInterval(show_next_live_notify, (showtime + <?php print $s + 100; ?>));
}
setTimeout(startMe, 10000);
You function name is show_live_feed_notify, and you tried to use setTimeout. Therefore I suggest you to try the following:
var delay = 10000; // 10 seconds
setTimeout(function() {
show_live_feed_notify(current_index + 1);
}, delay )

javascript check for specific characters

I am trying to create a timer in javascript, and I have got it working, however I am trying to validate the users input, for the time. Currently it will accept anything as long as the inputbox is not empty. But I am wanting to only allow numbers, colon (:) and periods (.), I have looked at several questions, but most seem to be only checking for all text characters.
Here is the working code: https://jsfiddle.net/hLqayL1w/
OR
HTML:
<div class="maincont">
<h2>Please enter a amount of time</h2>
<p id="timer">0:00</p>
<div class="container">
<input id="request" type="text" placeholder="Time">
<button type="submit" class="click">Start timer</button>
</div>
<P id="cancelbutton" class="cancel">Cancel timer</P>
</div>
JS:
$(document).ready(function() {
$('#cancelbutton').hide();
});
$('.click').click(function() {
var conts = $('#request').val();
if ($('#request').val() === "") {
return;
}
$('.container').hide();
$('#cancelbutton').fadeIn('slow');
var rawAmount = $('#request').val();
var cleanAmount = rawAmount.split(':');
var totalAmount = parseInt(cleanAmount[0] | 0) * 60 + parseInt(cleanAmount[1] | 0);
$('#request').val(" ");
var loop, theFunction = function() {
totalAmount--;
if (totalAmount == 0) {
clearInterval(loop);
$('#cancelbutton').hide();
$('.container').fadeIn('slow');
}
var minutes = parseInt(totalAmount / 60);
var seconds = parseInt(totalAmount % 60);
if (seconds < 10)
seconds = "0" + seconds;
$('#timer').text(minutes + ":" + seconds);
$('#cancelbutton').click(function() {
totalAmount = 1
});
};
var loop = setInterval(theFunction, 1000);
})
In your example you just check if the input is an empty string lets change that so we check if it matches an regular expression:
if (!$('#request').val().match(/[0-9:.]/gi)) {
return;
}
We make it look for numbers,colons and dots everything else will not match and the return will run.
Here is an working example.
(This is just an quick and dirty example it is not showcasing that the regex should be written in this way, there probably are better ways to write this)
How about this?
$('#request').keyup(function() {
var el = $(this),
val = el.val();
el.val(val.replace(/[^\d\:.]/gi, ""));
}).blur(function() {
$(this).keyup();
});
It will check check if the input is number/./:, if not it will remove it live.
$(document).ready(function() {
$('#cancelbutton').hide();
});
$('#request').keyup(function() {
var el = $(this),
val = el.val();
el.val(val.replace(/[^\d\:.]/gi, ""));
}).blur(function() {
$(this).keyup();
});
$('.click').click(function() {
var conts = $('#request').val();
if ($('#request').val() === "") {
return;
}
$('.container').hide();
$('#cancelbutton').fadeIn('slow');
var rawAmount = $('#request').val();
var cleanAmount = rawAmount.split(':');
var totalAmount = parseInt(cleanAmount[0] | 0) * 60 + parseInt(cleanAmount[1] | 0);
$('#request').val(" ");
var loop, theFunction = function() {
totalAmount--;
if (totalAmount == 0) {
clearInterval(loop);
$('#cancelbutton').hide();
$('.container').fadeIn('slow');
}
var minutes = parseInt(totalAmount / 60);
var seconds = parseInt(totalAmount % 60);
if (seconds < 10)
seconds = "0" + seconds;
$('#timer').text(minutes + ":" + seconds);
$('#cancelbutton').click(function() {
totalAmount = 1
});
};
var loop = setInterval(theFunction, 1000);
})

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

Having issues with live calculations, calculating each key stroke

I have a table that calculates a total depending on the input the user types. My problem is that the jquery code is calculating each key stroke and not "grabbing" the entire number once you stop typing. Code is below, any help woud be greatly appreciated.
$(document).ready(function() {
$('input.refreshButton').bind('click', EstimateTotal);
$('input.seatNumber').bind('keypress', EstimateTotal);
$('input.seatNumber').bind('change', EstimateTotal);
});
//$('input[type=submit]').live('click', function() {
function EstimateTotal(event) {
var tierSelected = $(this).attr('data-year');
var numberSeats = Math.floor($('#numberSeats_' + tierSelected).val());
$('.alertbox_error_' + tierSelected).hide();
if (isNaN(numberSeats) || numberSeats == 0) {
$('.alertbox_error_' + tierSelected).show();
} else {
$('.alertbox_error_' + tierSelected).hide();
var seatHigh = 0;
var seatLow = 0;
var seatBase = 0;
var yearTotal = 0;
var totalsArray = [];
var currentYear = 0;
$('.tier_' + tierSelected).each(function() {
seatLow = $(this).attr('data-seat_low');
firstSeatLow = $(this).attr('data-first_seat_low');
seatHigh = $(this).attr('data-seat_high');
seatBase = $(this).attr('data-base_cost');
costPerSeat = $(this).attr('data-cost_per_seat');
years = $(this).attr('data-year');
seats = 0;
if (years != currentYear) {
if (currentYear > 0) {
totalsArray[currentYear] = yearTotal;
}
currentYear = years;
yearTotal = 0;
}
if (numberSeats >= seatHigh) {
seats = Math.floor(seatHigh - seatLow + 1);
} else if (numberSeats >= seatLow) {
seats = Math.floor(numberSeats - seatLow + 1);
}
if (seats < 0) {
seats = 0;
}
yearTotal += Math.floor(costPerSeat) * Math.floor(seats) * Math.floor(years) + Math.floor(seatBase);
});
totalsArray[currentYear] = yearTotal;
totalsArray.forEach(function(item, key) {
if (item > 1000000) {
$('.totalCost_' + tierSelected + '[data-year="' + key + '"]').append('Contact Us');
} else {
$('.totalCost_' + tierSelected + '[data-year="' + key + '"]').append('$' + item);
}
});
}
}
You'll need a setTimeout, and a way to kill/reset it on the keypress.
I'd personally do something like this:
var calc_delay;
$(document).ready(function() {
$('input.refreshButton').bind('click', runEstimateTotal);
$('input.seatNumber').bind('keypress', runEstimateTotal);
$('input.seatNumber').bind('change', runEstimateTotal);
});
function runEstimateTotal(){
clearTimeout(calc_delay);
calc_delay = setTimeout(function(){ EstimateTotal(); }, 100);
}
function EstimateTotal() {
....
What this does is prompt the system to calculate 100ms after every keypress - unless another event is detected (i.e. runEstimateTotal is called), in which case the delay countdown resets.

Categories