patternjavascriptMinor
Time lag on change function
Viewed 0 times
functionlagchangetime
Problem
I have a script to load a range of number. This range of number is only 200 lengths. However, it has a change function. When the start number is change, the the end number will try to find its range again.
The whole of code is working fine. However, it gives me a time lag (sometime get crash) on each change.
Can anyone help me to clean this code, please?
The whole of code is working fine. However, it gives me a time lag (sometime get crash) on each change.
Can anyone help me to clean this code, please?
function pad (str, max)
{
str = str.toString();
return str.length "+(c+l)+"");
}
var $auto = $('#automatic'),
$manual = $('#manual'),
lastValue = +$manual.find('option').last().val();
$manual.on('change', function () {
var value = +$(this).val(),
max = lastValue;
//alert(max);
$auto.empty();
for (var i = value; i ',
{
value:i+1,
text: i+1
}).appendTo($auto);
}
}).change()
});
01
02
03
04
05
06
07
11
22
33
44
55
66
77
Solution
Code hygiene
What is
You are sloppy in localizing your variables.
Take care to end your statements with a semicolon. It's considered good practice even though the language doesn't require them.
Performance
There are two major problems.
The first issue is that it is much more efficient to append a giant string all at once than to manipulate the DOM an element at a time.
The second problem is that you are defining a change handler within a change handler. That means the
What is
$("#serial")? Did you mean $("#manual").empty() instead?You are sloppy in localizing your variables.
a, b, j, k, c, l, lastValue, and max (the one in the $manual.on('change') handler) are all global. All of them are horribly named. Furthermore, I recommend eliminating unnecessary variables.Take care to end your statements with a semicolon. It's considered good practice even though the language doesn't require them.
Performance
There are two major problems.
The first issue is that it is much more efficient to append a giant string all at once than to manipulate the DOM an element at a time.
The second problem is that you are defining a change handler within a change handler. That means the
#manual element gets regenerated more and more frantically with each change in the first two columns.function pad(str, max) {
str = str.toString();
return str.length ' + i + '';
}
$('#automatic').html(autoOptions);
});
$("#game, #camp").on('change', function() {
var gameCamp = pad($('#game').val(), 2) +
pad($('#camp').val(), 2);
var manualOptions = '';
for (var i = 1; i ' + gameCamp + iii + '';
}
$('#manual').html(manualOptions)
.change();
});
01
02
03
04
05
06
07
11
22
33
44
55
66
77
Context
StackExchange Code Review Q#88095, answer score: 3
Revisions (0)
No revisions yet.