Uahnbu Tran
Uahnbu Tran

Reputation: 109

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.

Upvotes: 1

Views: 66

Answers (2)

Angelos Chalaris
Angelos Chalaris

Reputation: 6767

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 fixed 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"/>

Upvotes: 1

Keith Nicholas
Keith Nicholas

Reputation: 44308

an object might be easier :-

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

not sure if your 'b' is a global variable or just forgot to put var, if its global you will need

b = o.b 

at the end...though, if you are doing that, you're likely making a bit of a mess.

Upvotes: 2

Related Questions