I have a function to know what exact time and days an employee works.
That function returns a value that is used in a datepicker. As said, I only want to display the "working hours," so I had to disable the "non-working" hours.
var invalid_a = [
"2021-03-17T13:00:00.000Z",
"2021-03-17T13:00:00.000Z",
"2021-03-17T13:00:00.000Z",
"2021-03-17T13:00:00.000Z",
"2021-03-17T13:00:00.000Z",
"2021-03-17T13:00:00.000Z"
];
var invalid_b = [
"2021-03-17T22:00:00.000Z",
"2021-03-17T22:00:00.000Z",
"2021-03-17T22:00:00.000Z",
"2021-03-17T22:00:00.000Z",
"2021-03-17T22:00:00.000Z",
"2021-03-17T22:00:00.000Z"
];
var days_list = [
"MO",
"WE",
"TH",
"TU",
"FR",
"SA"
];
var comb = invalid_a.map(function combineTitleData(dataItem, index) {
let y = new Date(dataItem);
let mins = y.getMinutes() + 59;
return {
start: '00:00',
end: '' + y.getHours() - 1 + ':' + '' + mins + '',
recurring: { repeat: 'weekly', weekDays: days_list.toString() }
};
});
var comb2 = invalid_b.map(function combineTitleData(dataItem, index) {
return {
start: '' + new Date(dataItem).getHours() + ':' + '01',
end: '23:59',
recurring: { repeat: 'weekly', weekDays: days_list.toString() }
};
})
console.log(comb);
console.log(comb2);
When I test this works well, some users (a couple of them) have reported that the browser freezes when this function is executed, a pop-up appears with: "Page Unresponsive" - You can wait for it to become responsive or exit the page.
I know this is the function causing this because when I disabled this code on the page and tried again, everything was working fine.
Why is this function causing this in some browsers/clients? Is there a different way to map the dates with my expected output that won't cause browser errors?
Thanks.
Alike @ArkyAsmal answer, I advise you to use web workers or, more easily, if your array is composed of millions of entries, just add a little timeout to flush the UI thread every ~10k iterations:
map in a for loopawait new Promise(res => setTimeout(res, 5)) if i%1E5===0This appears to be a performance issue. The time complexity is O(n), but if they contain thousands of data points, its a bad time.
Javascript is a single threaded language, so if there are a lot of employees/data points to compute, the browser will wait until completing this entire data analysis, before doing anything else (i.e any clicks on buttons, links, etc).
This can and will crash the UI if there are a lot of data points, making the page unresponsive.
This is actually a great candidate for asynchronous javascript programming.
Solutions:
Use web.worker api to use additional cpu threads to do this computation. By default, this makes these function asynchronous
Convert these functions to javascript promises, thereby allowing the UI to still respond, because the function calculations are offloaded.
Here is a good resource if you want to look into either: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise