user6743729 user6743729 - 1 year ago 86 Question

Adding a back-end function call within a case statement from javascript is causing significant slow down

Adding a code-behind function call within a case statement in JavaScript front-end is causing a significant slow down even if the case being addressed isn't the one with the function.

// Gets info from updatepanel display once it's been updated
function EndRequestHandler() {
switch (tab) {
case 'A':
cData = JSON.parse('<%=func1() %>');
console.log(cData[0].municipality + ' ' + cData[0].lat + ' ' + cData[0].lng);

case ('B' || 'C'):
lat = document.getElementById('<%=label1.ClientID%>').textContent;
lng = document.getElementById('<%=label1.ClientID%>').textContent;
console.log(lat + ' long ' + lng);

if (vLat.length == 0 || vLng.length == 0) {
if (tab == 'B') {
eMsg = 'Invalid Zip Code.';
} else{
eMsg = 'Invalid Coordinates.';
} else {
};// end switch()

};// end EndRequestHandler()

If I comment out
case 'A'
and test
the application works very quickly, the minute I add
case 'A'
it slows down the whole thing, even if I'm only testing
, or

Answer Source

First of all, Javascript does not allow multiple case values in a single case like that. What actually happens is it evaluates ('B' || 'C') as an expression, which equals 'B'. So case ('B' || 'C'): really only matches 'B'. To match either 'B' or 'C', you must use two case statements:

case 'B': case 'C':

They can be on one line as shown, or on separate lines. Since there is no break in-between them, case 'B' will fall through into case 'C'. The code underneath will run if the tab variable is equal to either 'B' or 'C', as you probably intended.

As far as the slowness, I expect that <%=func1() %> is your problem. You're calling a secondary function, func1, in your ASP code, in order to pass data to the Javascript. The ASP runs on the server when the page is initially loaded, before the Javascript code even starts to run; this is why it's slowing down your code no matter whether that case statement runs or not.

I recommend inspecting that function to find out why it's slow, or refactoring the code so you don't need to use that function to pass that data from ASP to the page; for instance, you could use AJAX to download it from the server if that case actually runs; then it shouldn't slow down the other cases at all.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download