7

For some reason I got stuck with this 'thing'

As you can see I want to try to read the count.txt. This is working perfectly but for some reason the

alert(code);

is coming up after the

alert("The number can't be smaler then 0");

For me it makes no sense because I'd call the alert(count) before the alert("The number...") Any ideas why the jQuery function (alert) is called after the other alert?

function leftFunction() {
    jQuery.get('count.txt', function(data) {
        var count = data;
        alert(count);
    });
    scrolling = true;
    if(number == 0) {
        alert("The number can't be smaler then 0");
        return;
    }
    number--;
    document.getElementById("myImage").src = "latest" + number + ".jpg";
}
3
  • 6
    That's related to being sync/async. Check this out : stackoverflow.com/questions/27012556/… Commented Oct 26, 2017 at 7:35
  • 2
    jQuery.get() callback function is asynchronous "If the request is already complete, the callback is fired immediately." Commented Oct 26, 2017 at 7:38
  • Thanks alot for helping me :) Commented Oct 26, 2017 at 7:58

1 Answer 1

3

As Red fx says in the comments, it's related to JavaScript being asynchronous. Try something like this instead:

function leftFunction() {
    jQuery.get('count.txt', function(data) {
        var count = data;
        alert(count);
    }).done(function() {
        scrolling = true;
        if (number == 0) {
            alert("The number can't be smaler then 0");
            return;
        }
    });
    number--;
    document.getElementById("myImage").src = "latest" + number + ".jpg";
}

Reference: https://api.jquery.com/jquery.get/

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

1 Comment

Thanks alot for the snippet :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.