mutliple set timeouts running at once - javascript

so, i have a for loop that I want to run multiple set timeouts at once so it can continually check if it is a certain time for multiple times. i can't just check for all multiple times all at once, the check needs to repeat after different amounts of time. it only continues to repeat the last iteration of the loop, the last dict in lat.
my approach simplified a bit:
lat = list of dictionaries with some values that differentiate them + times
for(i = 0; i< lat.length; i++){
if(lat[i][differentiate value]) = {
function checktime(){
if(currenttime != lat[i]){
setTimeout(checktime,30000)
}
else{
console.log("yay the time is right!")
}
}
else if(lat[i][differentiate value]) = {
function checktime(){
if(currenttime != lat[i]){
setTimeout(checktime,50000)
}
else{
console.log("yay the time is right!")
}
}
}
How would I go about making this (its for a notification app)
original code:
(each value in later looks like [[75,null,[7,28,2021]], null,[[9,52,"p"]],"e&r"] with the amount of notifications, a preset date, the date for these reminders to be on, by time, which would be the first if, and the array of at times. for testing I had 2 laters with 2 different at times):
chrome.storage.sync.get('later', function(data){
if (data.later !== null){
var lat = data.later;
for(i = 0; i< lat.length; i++){
var currentDict = lat[i];
if(currentDict['notis'][1] !== null){
console.log("cheese")
var by = currentDict['notis'][1];
console.log(by)
const d = new Date();
var hr = d.getHours();
var min = d.getMinutes();
var sec = d.getSeconds();
var da = currentDict['notis'][0][2][1];
var mo = currentDict['notis'][0][2][0];
var ye = currentDict['notis'][0][2][2]
var h = by[0];
var m = by[1];
var ampm = by[2];
if(ampm == "p"){
h = h + 12;
}
var byMS = h*3600000 + m*60000;
var currentMS = hr*3600000 + min*60000 + sec*1000;
//check if right date then check if time is lesss than
function checkdate(){
var day = d.getDate();
var month = d.getMonth() + 1;
var year = d.getFullYear();
if(da == day && mo == month && ye == year){
var amt = 0;
function checktime(){
if(byMS >= currentMS){
//noti and delete
var int = setInterval(function(){
chrome.notifications.create({
title: currentDict['name'],
message: "do da " + currentDict['name'],
iconUrl: "logo.png",
type: "basic"
})
amt++
console.log(amt)
const dddd = new Date();
console.log(dddd.getMinutes() + " / " + dddd.getSeconds())
if(amt >= currentDict['notis'][0][0]){
clearInterval(int)
console.log("done")
//ju finish taht
console.log(lat)
lat.splice(lat.indexOf(currentDict),1)
console.log(lat)
chrome.storage.sync.set({'later': lat})
}
}, (byMS-currentMS)/currentDict['notis'][0][0])
}
else{
setTimeout(checktime,30000)
}
}
checktime();
}
else{
setTimeout(checkdate,66400000)
}
}
checkdate();
}
else if(currentDict['notis'][2] !== null){
console.log("cheese")
var at = currentDict['notis'][2];
console.log(at)
var arrayat = [];
for(j = 0; j<= at.length-1; j++){
var atcycle = at[j];
console.log(atcycle)
const ddd = new Date();
var hr = ddd.getHours();
var min = ddd.getMinutes();
var da = currentDict['notis'][0][2][1];
var mo = currentDict['notis'][0][2][0];
var ye = currentDict['notis'][0][2][2]
var hrat = atcycle[0];
var minat = atcycle[1];
var ampm = atcycle[2];
if(ampm == "p"){
hrat = hrat + 12;
}
console.log(hrat + "/" + minat + "/" + ampm)
if(hr <= hrat){
var temparray = [];
temparray.push(hrat)
temparray.push(minat)
arrayat.push(temparray);
console.log(arrayat)
}
else if(hr == hrat){
if(min<minat){
var temparray = [];
temparray.push(hrat)
temparray.push(minat)
arrayat.push(temparray);
console.log(arrayat)}
}
}
console.log(arrayat.length)
function checkdate(){
console.log(arrayat.length)
console.log("date")
const d = new Date();
var day = d.getDate();
var month = d.getMonth() + 1;
var year = d.getFullYear();
if(da == day && mo == month && ye == year){
function check(){
console.log(arrayat.length)
console.log("check")
for(l=0; l<arrayat.length; l++){
console.log(arrayat.length)
const dd = new Date();
var hr = dd.getHours();
var min = dd.getMinutes();
console.log(arrayat[l][1])
console.log(min)
if(arrayat[l][0] == hr && arrayat[l][1] == min ){ //at one of the times
console.log(arrayat)
arrayat.splice(l,1)
console.log(arrayat)
if(arrayat.length == 0){
lat.splice(lat.indexOf(currentDict),1)
chrome.storage.sync.set({'later': lat})
console.log(lat)
}
chrome.notifications.create({
title: currentDict['name'],
message: "do da " + currentDict['name'],
iconUrl: "logo.png",
type: "basic"
})
//add noti with name and delete it
console.log(arrayat)
check();
}
}
console.log(arrayat.length)
if(arrayat.length !== 0){
console.log("and repeat")
setTimeout(check,15000);//SETINTERVAL INSTEAD? ANDCLEAR
}
}
check();
}
else{
setTimeout(checkdate,66400000)
}
}
checkdate();
}
}
}
})
}

This is the wrong approach. You know the times, so you know how far off they are in time. You don't need to check over and over again if the time has arrived. Instead work out how many milliseconds until the time in question, then set a timeout for that time.

You basically need to pass different functions to each setTimeout():
function checktime1(){
if(currenttime != lat[i]){
setTimeout(checktime1,30000)
}
else{
console.log("yay the time is right!")
}
}
function checktime2(){
if(currenttime != lat[i]){
setTimeout(checktime2,50000)
}
else{
console.log("yay the time is right!")
}
}
However, this is obviously not scalable. If you have lots of timeouts you will be writing lots of duplicate functions. Worse, if you have a dynamic number of timeouts this won't solve your problem.
Fortunately, javascript lets us declare functions inside another function:
function checktime(timeout){
function loop () {
if(currenttime != lat[i]){
setTimeout(loop,timeout)
}
else{
console.log("yay the time is right!")
}
}
loop();
}
This allows you to dynamically create functions as needed:
checktime(30000);
checktime(50000);
If you need to pass arguments to each timeouts (eg. if you need to display custom alerts) you can just pass it to your outer function and it will be captured in a closure:
function checktime(timeout, message){
function loop () {
if(currenttime != lat[i]){
setTimeout(loop,timeout)
}
else{
console.log(message)
}
}
loop();
}
Then you can do:
checktime(30000, "Yay, the time is right for timer 1");
checktime(50000, "Yay, the time is right for timer 2");
Similarly, if you need to execute custom logic for each timer you can also pass it as an argument (callback):
function checktime(timeout, callback){
function loop () {
if(currenttime != lat[i]){
setTimeout(loop,timeout);
}
else{
console.log("yay the time is right!");
callback(); // <----------------- execute custom logic
}
}
loop();
}
Which you can use like:
checktime(30000, () -> console.log("TIMER 1"));
checktime(50000, () -> alert("TIMER 2"));

Related

Date range for cash flows

I am trying to create a cash flow with dates.
I have 2 dates: Start and End
If payments are monthly and suppose the rent payment day is on 15th. Then the cashflow would :
10/15/2018
11/15/2018
12/15/2018
1/15/2019..... and so forth until the end date.
Similarly if rent is paid every 3 months then cashflow would look like:
10/15/2018 1/15/2018 4/15/2018... and so forth.
I have the following code which works every time except when the rent is on 1st day of the month or last day of the month.
function createLedger(stDate, etDate){
if (stDate && etDate) {
var d2 = new Date(etDate);
var sDay = d2.getUTCDate();
var sMonth = d2.getUTCMonth() + 1;
var sYear = d2.getUTCFullYear();
var endOfLeaseDate = sYear + "-" + sMonth + "-" + sDay;
var d3 = new Date(stDate);
var s1Day = d3.getUTCDate();
var s1Month = d3.getUTCMonth() + 1;
var s1Year = d3.getUTCFullYear();
var startOfLeaseDate = s1Year + "-" + s1Month + "-" + s1Day;
var ddlFrequency = document.getElementById("ddFrequency");
var selectedFrequency = ddlFrequency.options[ddlFrequency.selectedIndex].value;
if (selectedFrequency) {
if (selectedFrequency == "D") {
dates = dateRange(startOfLeaseDate, endOfLeaseDate);
}
Here is where the issue is:
else if (selectedFrequency == "Q") {
dates = getQuartersDateRange(d3, d2)
dates = SortedQuarter(d3,dates);
}
else {
dates = [];
}
}
else {
dates = [];
}
createFormElement();
}
}
And i have the following codes to get the date range and quarter range.
function getQuartersDateRange(startOfLeaseDate, endOfLeaseDate) {
var dates = [];
var qlist = listQuarters(startOfLeaseDate, endOfLeaseDate);
for (var i = 0; i < qlist.length; i++) {
var yearquarter = qlist[i].split('-');
var dateQ = new Date(yearquarter[0], (yearquarter[1] * 3 - 3) + 1, startOfLeaseDate.getUTCDate());
qDay = dateQ.getUTCDate();
qMonth = dateQ.getUTCMonth();
qYear = dateQ.getUTCFullYear();
var qDate = qYear + "-" + qMonth + "-" + qDay;
dates.push(qDate);
}
return dates;
}
function SortedQuarter(startOfLeaseDate, dates) {
var qdatesSorted = [];
for (var j = 0; j < dates.length; j++) {
var month;
var splitDate = dates[j].split('-');
if (j == 0)
month = startOfLeaseDate.getUTCMonth() + 1;
else {
startOfLeaseDate.setMonth(startOfLeaseDate.getUTCMonth() + 3)
month = startOfLeaseDate.getUTCMonth() + 1;
}
var qDate = splitDate[0] + "-" + month + "-" + splitDate[2];
qdatesSorted.push(qDate);
}
return qdatesSorted;
}
function listQuarters(sDate, eDate) {
if (sDate > eDate) {
var t = eDate;
eDate = sDate;
sDate = t;
}
sDate = new Date(sDate);
sDate.setDate(2);
var startQ = getQuarter(sDate);
var endQ = getQuarter(eDate);
var result = [startQ];
while (startQ != endQ) {
sDate.setMonth(sDate.getUTCMonth() + 3);
startQ = getQuarter(sDate);
result.push(startQ);
}
return result;
}
The issue here is that when the start date = 11/1/2018 and end date = 01/31/2020
the cashflow prints as follows
11/1/2018 3/1/2019 6/1/2019 9/1/2019 12/1/2019...and so forth. So instead of going from 11/1/2018 to 2/1/2018, it skips the month and goes to the next one. I am not sure why it does that only towards the end of the month or the beginning of the month.
Any help is appreciated. Thank you.
Using moment library worked for me. aLSO, I rewrote the date range as follows:
function createLedger(stDate, etDate) {
if (stDate && etDate) {
var endOfLeaseDate = moment(etDate, "MM/DD/YYYY");
var startOfLeaseDate = moment(stDate, "MM/DD/YYYY");
dateRange(startOfLeaseDate, endOfLeaseDate);
}
}
function dateRange(stDate, etDate) {
var dates = [];
var now = etDate.clone();
var day = etDate.date();
while(now.isAfter(stDate)) {
var month = now.clone().endOf("month");
if (now.date() < day && day <= month.date()) {
now.date(day);
}
dates.push(now.format("MM/DD/YYYY"));
//dates._reverse();
now = now.clone().subtract({"months": 1});
}
console.log(dates);
}
function RunLedgerAndPV() {
var stDate = "11/26/2018";
var etDate = "09/25/2019";
createLedger(stDate, etDate);
}
RunLedgerAndPV();

Stop execute ajax in for loop

I'm trying to do the following. Get number of pages from the API. Each page has multiple results. I check all the results with my condition. If the result fits the condition, then I need to finish the check, finish the page search and pass the result to another function. I don't understand how to end ajax (getData() execution in the checkPages() function) and exit the for loop in the same place. The break and return keywords do not help. Please tell me how to do it. Maybe I need to do to refactor my code. I don't really like to "throw" results from a function into a function. I do not use async/await because I need compatibility with old browsers.
getData("url-to-get-data").done(function (result) {
checkPages(result.total_pages);
});
function getData(url) {
return $.get({
url: "url-to-get-data"
})
}
function checkPages(pagesCount) {
for (var i = 2; i <= pagesCount; i++) {
getData("url-to-get-data", i).done(function(result) {
var today = checkToday(result);
if (today != null) {
//someMethod
//how to end the getData function and the for loop
}
});
}
}
function checkToday(response) {
var results = response.results;
var today = new Date();
var day = today.getDate();
var month = today.getMonth();
for (var i = 0; i < results.length; i++) {
var d = new Date(results[i].release_date);
if (d.getDate() === day && d.getMonth() === month) {
return results[i];
}
}
return null;
}
simplest change to your checkPages function
inner function that calls itself as required
function checkPages(pagesCount) {
function checkPage(i) {
if (i <= pagesCount) {
getData("url-to-get-data", i).done(function(result) {
var today = checkToday(result);
if (today == null) { // only get next page if today is null
checkPage(i+1);
}
});
}
}
checkPage(2);
}
If I understand correctly you are trying to do something like this?
UPDATE: implemented que to check if request is finsihed
getData("url-to-get-data").done(function (result) {
checkPages(result.total_pages);
});
function getData(url) {
return $.get({
url: "url-to-get-data"
})
}
function checkPages(pagesCount) {
let doContinue = true;
let loading = false;
let i = 2;
var checker = setTimeout(()=>{
if(i > pagesCount) clearTimeout(checker);
if(!loading){
loading = true;
getData("url-to-get-data", i).done(function(result) {
var today = checkToday(result);
if (today != null) {
clearTimeout(checker);
}
i++;
loading = false;
});
}
},100);
}
function checkToday(response) {
var results = response.results;
var today = new Date();
var day = today.getDate();
var month = today.getMonth();
for (var i = 0; i < results.length; i++) {
var d = new Date(results[i].release_date);
if (d.getDate() === day && d.getMonth() === month) {
return results[i];
}
}
return null;
}
Make your ajax call synchronous or use callback functions to keep getting more data until conditions are met.

Getting the JavaScript inside the codebehind to return true or false?

I'm having an issue with calling a JavaScript function while in the codebehind method:
This code populates the textboxes with the cookieValues data. The JavaScript CalculateDOBAge gets called and does an existing DOB calculation and determines if the Age being returned is the same age as the DOB being returned.
However, if it determines that the DOB calculates a different Age then what is being returned I want to clear out the txtDOB and txtMonths textboxes. This is the part that isn't working.
ASP.Net Code Behind:
private void LoadSheetValues()
{
txtDOB.Text = cookieValues["DOB"];
txtAge.Text = cookieValues["Age"];
txtMonths.Text = cookieValues["Months"];
ClientScript.RegisterStartupScript(GetType(), "CalculateDOBAge", "calcDOBAge()", true);
}
JavaScript snippet:
if ((displayYear == age) && (displayMonth == months)) {
//The SAME
} else {
//Different
document.getElementById("txtDOB").value = '';
document.getElementById("txtMonths").value = '';
}
The javascript code is called from the ClientScript.RegisterStartupScript call and I can step through the values being blanked out. However, I think I dealing with a page lifecycle issue as when I check the screen after completion, the values remain in the textboxes.
I need the RegisterStartupScript (vs RegisterClientScriptBlock) as the CalculateDOBAge function needs the elements to be available and populated (so I can do the DOB calculation).
Is there a way to set this up using the RegisterStartupScript to return a True/False and then I can continue in the codebehind to clear out the textbox text?
Unfortunately this is an ancient application and jQuery or any modern frameworks are not available.
Full JavaScript:
function DOBAgeMonthCheck(birthDate, dateFormat) {
try {
if (dateFormat == 'MMDD') {
var bmo = birthDate.substr(0, 2);
var bday = birthDate.substr(3, 2);
var byr = birthDate.substr(6, 4);
} else if (dateFormat == 'DDMM') {
var bmo = birthDate.substr(3, 2);
var bday = birthDate.substr(0, 2);
var byr = birthDate.substr(6, 4);
} else if (dateFormat == 'YMD') {
var byr = birthDate.substr(0, 4);
var bmo = birthDate.substr(5, 2);
var bday = birthDate.substr(8, 2);
}
//replaces *ALL* "_" with ""
byr = byr.replace(/_/g, "");
bmo = bmo.replace(/_/g, "");
bday = bday.replace(/_/g, "");
var yrDiff;
var displayMonth;
var displayYear;
var now = new Date();
tday = now.getDate();
tmo = now.getMonth() + 1; //January is 0!
tyr = now.getFullYear();
//set four digit year
var tmpYr = tyr.toString();
byr = removeLeadingZero(byr);
var tmpLength = byr.length;
if (tmpLength < 4) {
if (byr > tmpYr.substr(2, 2))
byr = "1900".substr(0, 4 - tmpLength) + byr;
else
byr = "2000".substr(0, 4 - tmpLength) + byr;
}
if ((tmo > bmo) || (tmo == bmo & tday >= bday))
yrDiff = parseInt(byr)
else
yrDiff = parseInt(byr) + 1
if (tyr - yrDiff < 0)
displayYear = 0;
else
displayYear = (tyr - yrDiff);
if (tmo >= bmo)
displayMonth = tmo - parseInt(bmo);
else
displayMonth = 12 - (parseInt(bmo) - tmo);
var age;
var months;
try { age = document.getElementById("txtAge").value; } catch (err) { }
try { months = document.getElementById("txtMonths").value; } catch (err) { }
if ((displayYear == age) && (displayMonth == months)) {
//The SAME
} else {
//Different
document.getElementById("txtDOB").value = '';
document.getElementById("txtMonths").value = '';
}
}
catch (err) { }
}
I'm getting to the //Different section and watching the values being cleared.

Time overlap issue javascript

I am working in add task module in my project.i want to check every time task add check if existing tasks overlap or not. i am almost did but,one problem occur on time overlap condition not allow add task, example if user add tasks below times like below:
09:00 AM - 10:00 AM
10:30 AM - 11:00 AM
if i add tasks to between 10:00 AM to 10:30 AM not allowed in my condition on below:
function disabletime(start_time, end_time) {
var start_date = new Date(new Date(start_time).getTime());
var end_date = new Date(new Date(end_time).getTime());
var disable_times = new Array();
var max_date = 0;
var min_date = 0;
if (tasks_array.length > 0) {
for (var i = 0; i < tasks_array.length; i++) {
var prev_s_date = Date.parse("1-1-2000 " + tasks_array[i].start_time);
var prev_e_date = Date.parse("1-1-2000 " + tasks_array[i].end_time);
var prev_start_date = new Date(new Date(prev_s_date).getTime());
var prev_end_date = new Date(new Date(prev_e_date).getTime());
if (i == 0) {
min_date = prev_start_date.getTime();
max_date = prev_end_date.getTime();
} else {
if (prev_end_date.getTime() > max_date) {
max_date = prev_end_date.getTime();
}
if (prev_start_date.getTime() < min_date) {
min_date = prev_start_date.getTime();
}
}
}
if ((start_date.getTime() == min_date) && (end_date.getTime() == max_date)) {
alert("Check the start and end time for this task!");
return false;
} else if ((start_date.getTime() < min_date) && (end_date.getTime() <= min_date) || (start_date.getTime() >= max_date) && (end_date.getTime() > max_date)) {
} else {
alert("Check the start and end time for this task!");
return false;
}
}
start_date = new Date(start_date.getTime() + 30 * 60000);
while (start_date < end_date) {
disable_times.push([start_date.getHours(), start_date.getMinutes()]);
start_date = new Date(start_date.getTime() + 30 * 60000);
}
return true;
}
here is my code flow, i add all tasks into json array in javascript. every time add new task check existing tasks on json array objects(inside if tasks exist) time overlap or not.
Here is a fiddle
I think it's a 'refactor if you want to debug' case.
Just breaking you problems into well isolated, small, simple problems will lead you to a solution faster than any deep debug cession.
You should break down the complexity of your code by using objects,
so you'll have a clear view on who does what, and you can test
easily each part.
I'm not sure the code below complies with all your needs, but it
should be much easier to use : i defined 2 objects : a task,
and a set of task.
For each i defined pretty simple methods, easy to read and debug.
I did not test the result, but you'll get the idea on how to do what
you want from here.
http://jsfiddle.net/gamealchemist/b68Qa/2/
// ------------------------------
// Task
function Task(startDate, endDate) {
this.start = startDate;
this.end = endDate;
}
// returns wether the time range overlaps with this task
Task.prototype.overlap = function (start, end) {
return (this.start <= end && this.end >= start);
}
// returns a string describing why the task is wrong, or null if ok
function checkTask(start, end) {
if (start > end) return "End time should exceed the start time";
if (start == end) return "End time should not same as the start time";
return null;
}
and now a set of tasks :
// ------------------------------
// Task Set
function TaskSet() {
this.tasks = [];
this.minDate = 0;
this.maxDate = 0;
}
// returns a string describing why the task cannot be added, or null if ok
TaskSet.prototype.check = function (start, end) {
var tasks = this.tasks;
// 1. Check date is valid
var dateCheck = checkTask(start, end);
if (dateCheck) return dateCheck;
// 2. overlap check
for (var i = 0; i < tasks.length; i++) {
var thisTask = tasks[i];
if (thisTask.overlap(start, end)) {
return 'time overlaps with another task';
}
}
return null;
}
// add the task.
TaskSet.prototype.add = function (start, end) {
var tasks = this.tasks;
if (task.length) {
this.minDate = start;
this.maxDate = end;
}
if (start < minDate) minDate = start;
if (end > maxDate) maxDate = end;
// you might want to check before inserting.
tasks.push(new Task(start, end));
}
// displays the current task inside the tasks div.
TaskSet.prototype.show = function () {
var tasks_array = this.tasks;
$("#tasks").html('');
$.each(tasks_array, function (index, item) {
var newRowContent = "<div>" + item.start_time + "-" + item.end_time + "</div>";
$("#tasks").append(newRowContent);
});
}
Let's use those objects :
// ---------------------------
var myTasks = new TaskSet();
$("#addtask").click(handle_AddTask_Clicked);
function handle_AddTask_Clicked(e) {
e.preventDefault();
var start = $("#task_stime").val();
var end = $("#task_etime").val();
var start_time = Date.parse("1-1-2000 " + start);
var end_time = Date.parse("1-1-2000 " + end);
var checkCanAdd = myTasks.check(start_time, end_time);
if (!checkCanAdd) {
myTasks.add(start_time, end_time);
myTasks.show(); // notice you might auto-refresh withinin add
} else {
alert(checkCanAdd);
}
}
finally i got solution from my friends on below code:
function disabletime(start_time, end_time) {
var start_date = start_time;
var end_date = end_time;
var disable_times = new Array();
var max_date = 0;
var min_date = 0;
var startTimeOverlapIndex = -1;
var endTimeOverlapIndex = -1;
var sameDateIndex = -1;
if (tasks_array.length > 0) {
for (var i = 0; i < tasks_array.length; i++) {
var prev_s_date = new Date("January 1, 1111 " + tasks_array[i].start_time);
var prev_e_date = new Date("January 1, 1111 " + tasks_array[i].end_time);
if(end_date<=prev_e_date) {
if(end_date>prev_s_date) {
endTimeOverlapIndex = i+1;
break;
}
}
if(start_date<prev_e_date) {
if(start_date>=prev_s_date) {
startTimeOverlapIndex = i+1;
break;
} else {
if(end_date>prev_s_date) {
endTimeOverlapIndex = i+1;
break;
}
}
}
if(start_date.toString()===prev_s_date.toString() && end_date.toString()===prev_e_date.toString()) {
sameDateIndex = i+1;
break;
}
}
if(sameDateIndex>0) {
alert("Sorry! your time cannot be same as task ("+startTimeOverlapIndex+"), please check again!");
return false;
} else if(startTimeOverlapIndex>0) {
alert("Sorry! your START time is overlaping with task ("+startTimeOverlapIndex+"), please check again!");
return false;
} else if(endTimeOverlapIndex>0) {
alert("Sorry! your END time is overlaping with task ("+endTimeOverlapIndex+"), please check again!");
return false;
} else {
//do whatever you do
return true;
}
}
return true;
}
Live link on fiddle find here
http://jsfiddle.net/mur7H/
It is 100% working. Please find below the correct answer with date and time overlapping.
function isBetween(ST, ET, PST, PET) {
var res = false;
if (((ST - PST) * (ST - PET) <= 0) || ((ET - PST) * (ET - PET) <= 0) || ((PST - ST) * (PST - ET) <= 0) || ((PET - ST) * (PET - ET) <= 0)) res = true;
return res;
}
function disabletime(start_time, end_time) {
debugger;
var start_date = new Date(start_time);
var end_date = new Date(end_time);
var disable_times = new Array();
var max_date = 0;
var min_date = 0;
var startTimeOverlapIndex = -1;
var endTimeOverlapIndex = -1;
var sameDateIndex = -1;
var resultA = true;
if (KitchenHourList.length > 0) {
for (var i = 0; i < KitchenHourList.length; i++) {
var prev_s_date = new Date(KitchenHourList[i].KitchenFromDate + " " + KitchenHourList[i].KitchenFromTime);
var prev_e_date = new Date(KitchenHourList[i].KitchenToDate + " " + KitchenHourList[i].KitchenToTime);
var STMinut = (start_date.getHours() * 60) + start_date.getMinutes();
var ETMinut = (end_date.getHours() * 60) + end_date.getMinutes();
var PSTMinut = (prev_s_date.getHours() * 60) + prev_s_date.getMinutes();
var PETMinut = (prev_e_date.getHours() * 60) + prev_e_date.getMinutes();
if (end_date <= prev_e_date) {
if (end_date > prev_s_date) {
if (isBetween(STMinut, ETMinut, PSTMinut, PETMinut)) {
endTimeOverlapIndex = i + 1;
break;
}
}
}
if (start_date < prev_e_date) {
if (start_date >= prev_s_date) {
if (isBetween(STMinut, ETMinut, PSTMinut, PETMinut)) {
startTimeOverlapIndex = i + 1;
break;
}
} else {
if (end_date > prev_s_date) {
if (isBetween(STMinut, ETMinut, PSTMinut, PETMinut)) {
{
endTimeOverlapIndex = i + 1;
break;
}
}
}
}
}
if (start_date.toString() === prev_s_date.toString() && end_date.toString() === prev_e_date.toString()) {
sameDateIndex = i + 1;
break;
}
}
if (sameDateIndex > 0) {
alert("Sorry! your time cannot be same as row (" + startTimeOverlapIndex + "), please check again!");
return false;
} else if (startTimeOverlapIndex > 0) {
alert("Sorry! your START time is overlaping with row (" + startTimeOverlapIndex + "), please check again!");
return false;
} else if (endTimeOverlapIndex > 0) {
alert("Sorry! your END time is overlaping with row (" + endTimeOverlapIndex + "), please check again!");
return false;
} else {
return true;
}
}
return true;
}

How to delete and object from and array

Thanks for your help in advance. I have been trying for two days how to delete an object which is stored in an array and I dont get it. Just reading a lot on forums and trying, but nothing works.
<head>
<style>
</style>
<script type="text/javascript">
//Global Array to saved more than one object without having to declare all of them
var car = {};
var i;
var numRecords2 = 0;
var doors;
var outOfDateInsurance;
var contRecords = -1;
// Class Cars
function Cars(record, brand, color, doors, insurance, outOfDateInsurance)
{
this.record = record;
this.brand = brand;
this.color = color;
this.doors = doors;
this.insurance = insurance;
this.outOfDateInsurance = outOfDateInsurance;
}
//To validate number of the doors. It has to be 3 or 5
function validateDoors()
{
doors = prompt("Number of doors");
doors = parseInt(doors);
if (isNaN(doors) === false && (doors == 3 || doors == 5))
{
return;
}
else
{
alert("Wrong character. Please, set 3 or 5");
validateDoors();
}
}
//To validate date's format
function validateFormatDate(outOfDateInsurance)
{
var RegExPattern = /^\d{1,2}\/\d{1,2}\/\d{2,4}$/;
if ((outOfDateInsurance.match(RegExPattern)) && (outOfDateInsurance!=''))
{
return true;
}
else
{
return false;
}
}
//To check if the date is in the calendar
function realDate(outOfDateInsurance)
{
var fechaf = outOfDateInsurance.split("/");
var d = fechaf[0];
var m = fechaf[1];
var y = fechaf[2];
return m > 0 && m < 13 && y > 0 && y < 32768 && d > 0 && d <= (new Date(y, m, 0)).getDate();
}
//To validate the date is over today
function validateAboveDate(outOfDateInsurance)
{
var datef = outOfDateInsurance.split("/");
var d = datef[0];
var m = datef[1];
var y = datef[2];
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10)
{
dd='0'+dd
}
if(mm<10)
{
mm='0'+mm
}
var today = dd+'/'+mm+'/'+yyyy;
var todayf = today.split("/");
var dt = todayf[0];
var mt = todayf[1];
var yt = todayf[2];
if ((d > dt) && (m >= mt) && (y >= yt))
{
return true;
}
else
{
if ((d = dt) && (m > mt) && (y >= yt))
{
return true;
}
else
{
if ((d < dt) && (m > mt) && (y >= yt))
{
return true;
}
else
{
return false;
}
}
}
}
//To validate the date's is right
function checkingDate()
{
outOfDateInsurance = prompt("Insurance's End date (dd/mm/yyyy)");
if(validateFormatDate(outOfDateInsurance))
{
if(realDate(outOfDateInsurance))
{
if (validateAboveDate(outOfDateInsurance))
{
alert("Record has been introduced into the system");
}
else
{
alert("You have introduced an incorrect Insurance's End date");
checkingDate();
}
}
else
{
alert("You have introduced an incorrect Insurance's End date");
checkingDate();
}
}
else
{
alert("You have introduced an incorrect Insurance's End date");
checkingDate();
}
}
//To create objects
function addCar()
{
var numRecords = prompt("How many records do you want to introduce to the system?");
numRecords = parseInt(numRecords);
if (isNaN(numRecords) === false)
{
var istart = contRecords + 1;
var iend = numRecords2 + numRecords;
//problema aƱadiendo cars porque reemplaza si no lo hago todo de una vez
for (i = istart; i < iend; i++)
{
contRecords++;
var record = contRecords;
var brand = prompt("Car's Brand");
var color = prompt("Car's Color");
validateDoors();
var insurance = confirm("Does have the car insurance? Press OK for YES and CANCEL for NO");
if (insurance === true)
{
insurance = "Yes";
checkingDate();
}
else
{
insurance = "No";
alert("Record has been introduced into the system");
}
//CONSTRUCTOR We are creating the object car in the Class Cars
car[i] = new Cars(record, brand, color, doors, insurance, outOfDateInsurance);
}
numRecords2 = numRecords2 + numRecords;
}
else
{
alert("Please, introduce the number of the records you want to introduce");
addCar();
}
}
//To display the objects created
function displayCar()
{
document.getElementById("container").innerHTML = "";
for (i = 0; i < numRecords2; i++)
{
//we are creating an element <p>
var parag = document.createElement('p');
parag.id = "paragraph" + i;
//we are creating an element <br>
var br = document.createElement('br');
//we are creating a text node
var textRecord = document.createTextNode("Record: " + car[i].record);
var textBrand = document.createTextNode("Brand: " + car[i].brand);
var textColor = document.createTextNode("Color: " + car[i].color);
var textDoors = document.createTextNode("Number of doors: " + car[i].doors);
var textInsurance = document.createTextNode("Insurance: " + car[i].insurance);
if (car[i].insurance === "Yes")
{
var textOutOfDateInsurance = document.createTextNode("Date Insurance: " + car[i].outOfDateInsurance);
}
else
{
var textOutOfDateInsurance = document.createTextNode("Date Insurance: ");
}
//we are adding the text nodes created to the <p>
parag.appendChild(textRecord);
//We are creating a clone from a node to have multiple break lines
parag.appendChild(br.cloneNode());
parag.appendChild(textBrand);
parag.appendChild(br.cloneNode());
parag.appendChild(textColor);
parag.appendChild(br.cloneNode());
parag.appendChild(textDoors);
parag.appendChild(br.cloneNode());
parag.appendChild(textInsurance);
parag.appendChild(br.cloneNode());
parag.appendChild(textOutOfDateInsurance);
//we are adding the whole <p> with the text nodes into the div created in the html
document.getElementById("container").appendChild(parag);
}
}
function deleteCar()
{
car[0] = null;
car.splice(0);
for (i = 0; i <= contRecords; i++)
{
alert(car[i]);
}
//if (contRecords >=0)
//{
// var numRecordToDelete = prompt("Introduce the record's number you want to delete");
// numRecordToDelete = parseInt(numRecordToDelete);
// if (isNaN(numRecordToDelete) === false)
// {
// //var i = numRecordToDelete;
// //
// // alert('Record: ' + i);
// //if(car[i].record === 'Record: ' + i)
// //{
// // alert('Record: ' + i);
// // car.splice(i,1);
// // return false;
// //}
// car.shift();
// document.getElementById("container").innerHTML = car;
// }
// else
// {
// alert("The character you have introduce is not a number");
// deleteCar();
// }
//}
//else
//{
// alert("There are no any record to delete");
// return;
//}
}
</script>
</head>
<body>
<h1 style="text-align: center;">WELLCOME TO THE AMAZING SOFTWARE TO ADD CARS TO YOUR SYSTEM</h1>
<br><br>
<!-- Button to create the object car -->
<input type="button" value="Add Car" onclick="addCar()">
<!-- Button to display the objects created -->
<input type="button" value="See Cars" onclick="displayCar()">
<input type="button" value="Delete Cars" onclick="deleteCar()">
<BR>
<hr>
<BR>
<!-- Div which information's objects is going to be displayed -->
<div id="container"></div>
</body>
So the thing is, I am adding objects to the array like a BBDD and i dont know how to do it to delete one object from the array and re-organize the other objects in the array's positions like, if I delete the element's array number 2, then, the number 3 will be the second one and the fodth one would be the third, etc...
Thanks a lot, any doubt, please, let me know. I really appreciate your help.
//Global Array to saved more than one object without having to declare all of them
var car = [],
doors,
outOfDateInsurance;
// Class Cars
function Cars(record, brand, color, doors, insurance, outOfDateInsurance)
{
this.record = record;
this.brand = brand;
this.color = color;
this.doors = doors;
this.insurance = insurance;
this.outOfDateInsurance = outOfDateInsurance;
}
//To validate number of the doors. It has to be 3 or 5
function validateDoors()
{
doors = prompt("Number of doors");
doors = parseInt(doors);
if (isNaN(doors) === false && (doors == 3 || doors == 5))
{
return;
}
else
{
alert("Wrong character. Please, set 3 or 5");
validateDoors();
}
}
//To validate date's format
function validateFormatDate(outOfDateInsurance)
{
var RegExPattern = /^\d{1,2}\/\d{1,2}\/\d{2,4}$/;
if ((outOfDateInsurance.match(RegExPattern)) && (outOfDateInsurance!=''))
{
return true;
}
else
{
return false;
}
}
//To check if the date is in the calendar
function realDate(outOfDateInsurance)
{
var fechaf = outOfDateInsurance.split("/");
var d = fechaf[0];
var m = fechaf[1];
var y = fechaf[2];
return m > 0 && m < 13 && y > 0 && y < 32768 && d > 0 && d <= (new Date(y, m, 0)).getDate();
}
//To validate the date is over today
function validateAboveDate(outOfDateInsurance)
{
var datef = outOfDateInsurance.split("/");
var d = datef[0];
var m = datef[1];
var y = datef[2];
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10)
{
dd='0'+dd
}
if(mm<10)
{
mm='0'+mm
}
var today = dd+'/'+mm+'/'+yyyy;
var todayf = today.split("/");
var dt = todayf[0];
var mt = todayf[1];
var yt = todayf[2];
if ((d > dt) && (m >= mt) && (y >= yt))
{
return true;
}
else
{
if ((d = dt) && (m > mt) && (y >= yt))
{
return true;
}
else
{
if ((d < dt) && (m > mt) && (y >= yt))
{
return true;
}
else
{
return false;
}
}
}
}
//To validate the date's is right
function checkingDate()
{
outOfDateInsurance = prompt("Insurance's End date (dd/mm/yyyy)");
if(validateFormatDate(outOfDateInsurance))
{
if(realDate(outOfDateInsurance))
{
if (validateAboveDate(outOfDateInsurance))
{
alert("Record has been introduced into the system");
}
else
{
alert("You have introduced an incorrect Insurance's End date");
checkingDate();
}
}
else
{
alert("You have introduced an incorrect Insurance's End date");
checkingDate();
}
}
else
{
alert("You have introduced an incorrect Insurance's End date");
checkingDate();
}
}
//To create objects
function addCar()
{
var numRecords = prompt("How many records do you want to introduce to the system?");
numRecords = parseInt(numRecords);
if (isNaN(numRecords) === false)
{
var iend = numRecords;
//problema aƱadiendo cars porque reemplaza si no lo hago todo de una vez
for (var i = 0; i < iend; i++)
{
var brand = prompt("Car's Brand");
var color = prompt("Car's Color");
validateDoors();
var insurance = confirm("Does have the car insurance? Press OK for YES and CANCEL for NO");
if (insurance === true)
{
insurance = "Yes";
checkingDate();
}
else
{
insurance = "No";
alert("Record has been introduced into the system");
}
//CONSTRUCTOR We are creating the ARRAY car in the Class Cars
car.push(new Cars(car.length + 1, brand, color, doors, insurance, outOfDateInsurance));
}
}
else
{
alert("Please, introduce the number of the records you want to introduce");
addCar();
}
displayCar();
}
//To display the objects created
function displayCar()
{
document.getElementById("container").innerHTML = "";
for (var i = 0; i < car.length; i++)
{
//we are creating an element <p>
var parag = document.createElement('p');
parag.id = "paragraph" + i;
//we are creating an element <br>
var br = document.createElement('br');
//we are creating a text node
var textRecord = document.createTextNode("Record: " + car[i].record);
var textBrand = document.createTextNode("Brand: " + car[i].brand);
var textColor = document.createTextNode("Color: " + car[i].color);
var textDoors = document.createTextNode("Number of doors: " + car[i].doors);
var textInsurance = document.createTextNode("Insurance: " + car[i].insurance);
if (car[i].insurance === "Yes")
{
var textOutOfDateInsurance = document.createTextNode("Date Insurance: " + car[i].outOfDateInsurance);
}
else
{
var textOutOfDateInsurance = document.createTextNode("Date Insurance: ");
}
//we are adding the text nodes created to the <p>
parag.appendChild(textRecord);
//We are creating a clone from a node to have multiple break lines
parag.appendChild(br.cloneNode());
parag.appendChild(textBrand);
parag.appendChild(br.cloneNode());
parag.appendChild(textColor);
parag.appendChild(br.cloneNode());
parag.appendChild(textDoors);
parag.appendChild(br.cloneNode());
parag.appendChild(textInsurance);
parag.appendChild(br.cloneNode());
parag.appendChild(textOutOfDateInsurance);
//we are adding the whole <p> with the text nodes into the div created in the html
document.getElementById("container").appendChild(parag);
}
}
function deleteCar()
{
if (car.length >0)
{
var numRecordToDelete = prompt("Introduce the record's number you want to delete");
numRecordToDelete = parseInt(numRecordToDelete);
if (isNaN(numRecordToDelete) === false)
{
alert('Record: ' + numRecordToDelete);
if(numRecordToDelete >= car.length)
{
alert('Record: ' + numRecordToDelete);
car.splice(numRecordToDelete - 1,1);
displayCar();
return false;
}
else {
alert("Record not exist");
deleteCar();
}
}
else
{
alert("The character you have introduce is not a number");
deleteCar();
}
}
else
{
alert("There are no any record to delete");
return;
}
}
<h1 style="text-align: center;">WELCOME TO THE AMAZING SOFTWARE TO ADD CARS TO YOUR SYSTEM</h1>
<br><br>
<!-- Button to create the object car -->
<input type="button" value="Add Car" onclick="addCar()">
<!-- Button to display the objects created -->
<input type="button" value="See Cars" onclick="displayCar()">
<input type="button" value="Delete Cars" onclick="deleteCar()">
<BR>
<hr>
<BR>
<!-- Div which information's objects is going to be displayed -->
<div id="container"></div>
You can use Array.splice() to delete entries from an array.
Link
car.splice(0,1);
I should you work with an array of objects. Actually you work with an object how array where re many objects. With this is more easy foreach actual cars to add, see and delete.
car = [];
when add:
car.push(new Cars(record, brand, color, doors, insurance, outOfDateInsurance));
Other than that, I suggest you when you add or delete car, refresh data for the client can see changes and refreshing records number for deletes.
When your splice a element of array, the other elements after will move -1. For this reason must call displayCar() at the end.
var numRecordToDelete = prompt("Introduce the record's number you want to delete");
car.splice(numRecordToDelete,1);
I believe I understand what you are looking for and the example provided should address that, if not let me know.
<script>
var collectionOfObjects = [];
collectionOfObjects.push({name: "anObject1"});
collectionOfObjects.push({name: "anObject2"});
collectionOfObjects.push({name: "anObject3"});
collectionOfObjects.push({name: "anObject4"});
console.log("collectionOfObjects initial state");
console.log(collectionOfObjects);
console.log("deleteing 2nd member - this will delete the object even if other things have reference to it and not just remove it from the collection");
console.log("deleteing 2nd member - it will croupt the length of the array but we can fix that");
delete collectionOfObjects[2];
collectionOfObjects = collectionOfObjects.sort();
collectionOfObjects.length = collectionOfObjects.length - 1
console.log("collectionOfObjects after delete");
</script>
On a side note I just noticed you could do this also:
//To validate date's format
function validateFormatDate(outOfDateInsurance)
{
var RegExPattern = /^\d{1,2}\/\d{1,2}\/\d{2,4}$/;
return outOfDateInsurance.match(RegExPattern) && (outOfDateInsurance!='')
}

Categories

Resources