Uahnbu Tran Uahnbu Tran - 4 months ago 6
Javascript Question

How to deal with codes that are called many times in Javascript?

I'm working on a Javascript code that repeats some lines for a lot of times. I've tried putting these lines in a function as below

function rpit() {
a += 1; b += 1;
}
document.getElementById('button1').onclick = function() {
var a = +document.getElementById('inpA').value,
b = +document.getElementById('inpB').value;
rpit();
if (a == 5) rpit();
if (b == 10) rpit();
rpit();
}


But it seems that way does not work. How can I deal with these code? Thanks for your help.

Answer

There is a lot you should change in your code to make it work the way you intend it to work.

  • First off, assuming that you are checking for any button clicks, you should use document.getElementsByTagName() instead of document.getElementById(). Then iterate over the results and add an onclick listener like you did.
  • Secondly, one of the main problems is that rpit() does not have knowledge of a and b as they are neither local nor global, so define them at the very top with a value of 0.
  • Third big issue is that your .value on the input fields gets them as a string so if a=5, running a+=1 will make it a=51. This can be fixes by using parseInt() with the value and a second argument of 10 (meaning decimal system).

Based on these notes, I refactored your code to the following (the console.log() is to show you the results.

var a=0, b=0;
function rpit() {
    a += 1; b += 1;
}
var buttons = document.getElementsByTagName('button');
for(var i = 0; i < buttons.length; i++)
  buttons[i].onclick = function(){
    a = parseInt(document.getElementById('inpA').value, 10);
    b = parseInt(document.getElementById('inpB').value,10);
    rpit();
    if (a == 5) rpit();
    if (b == 10) rpit();
    rpit();
    console.log("a: "+a+", b: "+b);
}
<button >button</button>
<input id="inpA" value="5"/>
<input id="inpB" value="8"/>