0

So the page keeps freezing when i run this function on firefox and google chrome i tried using a for loop didn't work as expected any ideas?

Thanks

   function grab_users() {

    var start_id = document.getElementById('start_range');
    start_id = start_id.value;

    var end_id = document.getElementById('end_range');
    end_id = end_id.value;

    var grabbed = document.getElementById('grabbed_users');
    while (start_id < end_id) {
        $.ajax({
            url: "php/extract.php",
            type: 'GET',
            data: {'start_range': start_id},
            success: function(res) {
                var usernames = res;

                if (!usernames.valueOf() == "") {
                    usernames = usernames.replace('</br>', '');
                    grabbed.value += usernames + '\n';
                }
            }
        });
        start_id+=1;
    }
}
7
  • 3
    The page should indeed 'freeze' until it completes. How many iterations are we talking about? Commented Jan 31, 2015 at 9:35
  • Looks like the usual AJAX problem, updating grabbed from inside the callback... Commented Jan 31, 2015 at 9:38
  • So how do i do it right the way? Commented Jan 31, 2015 at 9:40
  • @elclanrs: The OP's not using anything inside the success handler that varies for the loop, so that part's okay. (Doing a huge number of overlapping ajax calls, on the other hand...) Commented Jan 31, 2015 at 9:48
  • 1
    note that start_id is a string, and adding 1 doesn't do what the OP thinks Commented Jan 31, 2015 at 9:49

1 Answer 1

2

the values of inputs are always strings, you must convert them to Numbers before you use them, otherwise both, the comparision and the incrementation of start_id will not give the expected results(what ends in a infinite loop):

var start_id = parseInt(document.getElementById('start_range').value,10);
var end_id = parseInt(document.getElementById('end_range').value,10);

Suppose your start_id is "20" and your end_id is "30". You'll start out with "20" < "30", which is true; then on the next loop, you'll append 1 to the start_id string, giving us "201" < "30". That's a string comparison, and so it's also true. Then "2011" < "30", which is also true. And so on.

Using numbers corrects this.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.