0

I have a function that gets values using for loops and puts them into 1 variable. This variable is them stuck in a form where its is then submitted. But the problem is that the for loop would finish looping by the time the value is entered and submitted. So everytime I test it, the variable "value" = 9999. Can anyone please tell me how to add 1 to variable every time the function loops? Thanks in advance.

function myFunction() {

 var value1;
 var value2;
 var value3;
 var value4;
 var value;

 for (value1 = 0; value1 < 10; value1++) {
  for (value2 = 0; value2 < 10; value2++) {
   for (value3 = 0; value3 < 10; value3++) {
    for (value4 = 0; value4 < 10; value4++) {
     value = value1.toString() + value2.toString() + value3.toString() + value4.toString() + '@2018';
     document.getElementById('pswd').value = value;
     document.getElementById('uid').value = 'test';
     document.getElementById('commentForm').submit();
    }
   }
  }
 }
}

var loop = setInterval(function() {
 myFunction(); 
}, 2000);
Rob
  • 14,107
  • 28
  • 46
  • 64
Blackmagyk
  • 70
  • 5

1 Answers1

1

If I'm reading your question correctly, you would like the number to go up by one each time the interval callback is called? You can accomplish this by keeping track of the value outside the function, and do a single increment each time the callback is called. However, you are using 4 variables to basically count from 0 to 9999. You can simplify that a lot by using one variable to increment. Then you can left pad it with zeroes. That would look like this.

var value = 0;

function myFunction() {
    var pswd = value.toString().padStart(4, 0) + '@2018';
    document.getElementById('pswd').value = pswd;
    document.getElementById('uid').value = 'test';
    document.getElementById('commentForm').submit();

    value++;
    if(value > 9999) {
        value = 0;
    }
}

var loop = setInterval(myFunction, 2000);

If you can't use padStart, you can use slice instead. You can replace that line with the following.

var pswd = ('0000' + value).slice(-4) + '@2018';
kamoroso94
  • 1,618
  • 1
  • 19
  • 19