Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

aymene chaabaoui
aymene chaabaoui
901 Points

JQuery call a function several times synchronously

hello

I have a function which I call every key pressed event, and I want to finish the function's instructions before the next call for example we have :

function A()
{
    //instruction 1
    //instruction 2
    //instruction 3
    //instruction 4
}

i want that function A() finish all the job ( instruction 1 to 4 ) before the next call so this is my function for more information :

var last = "";
var cities = [];
const path = 'http://localhost:8080';
var i = 0;
var strategy = function () {

    var strat = $('input[name="searchStrategy"]:checked').val();
    if (strat === 's') {
        return 'citiesStartingWith';
    }
    else if (strat === 'c') {
        return 'citiesContaining';
    }
    else if (strat === 'e') {
        return 'citiesEndingWith';
    }

}


$('.result').hide();

// and this the main function 
$('#search').on('keyup', function () {
        var valNow = $('#search').val();
        console.log(valNow + ' / ' + i);
        if (last !== valNow && valNow !== '') {
            //interrogate a server from a cities
            $.get(path + '/' + strategy() + '/' + valNow,
                function (data, status) {
                    if (status === 'success') {
                        cities = [];
                        cities = data;
                    }
                },
                'json');
            // make new last
            last = valNow;
            //list result
            var items = [];
            console.log(cities[0]);
            console.log(' / ' + i);
            $(cities).each(function (index, value) {
                console.log(value);
                var notStrong = valNow.length;
                var strong = value.length;
                items.push('<li><strong>'+ valNow +'</strong>'+value.substr(notStrong)+'</li>');
            });
            $('.result').append(items).show();
            i++;
        }
    }
);

2 Answers

Steven Parker
Steven Parker
230,274 Points

You shouldn't need to do anything special, it's the nature of JavaScript for events to be processed sequentially.

Here's an excerpt from the MDN page on Concurrency model and Event Loop:

Each message is processed completely before any other message is processed. This offers some nice properties when reasoning about your program, including the fact that whenever a function runs, it cannot be pre-empted and will run entirely before any other code runs.

aymene chaabaoui
aymene chaabaoui
901 Points

thank you so much for responding me , but when we use $.get method the function of this method takes time, for example here

$('#search').on('keyup', function () {
        var valNow = $('#search').val();
        console.log(valNow + ' / ' + i);
        if (last !== valNow && valNow !== '') {
            //interrogate a server from a cities
            $.get(path + '/' + strategy() + '/' + valNow,
                function (data, status) {
                   // just here
                    console.log(status);
                    if (status === 'success') {
                        cities = [];
                        cities = data;
                    }
                },
                'json');
            // make new last
            last = valNow;
            //list result
            var items = [];
            console.log(cities[0]);
            console.log(' / ' + i);
            $(cities).each(function (index, value) {
                console.log(value);
                var notStrong = valNow.length;
                var strong = value.length;
                items.push('<li><strong>'+ valNow +'</strong>'+value.substr(notStrong)+'</li>');
            });
            $('.result').append(items).show();
            i++;
            console.log('finish');
        }
    }
);

the console.log(status) statement is executed after console.log('finish') , so why after the finish statement and not before , because if you notice in the code : console.log(status) is located before console.log('finish'), and in the execution we have the opposit, so how to deal with this case study.

Steven Parker
Steven Parker
230,274 Points

The function that contains the "status" log message is called after the function containing the "finish" message. The one with the "status" message is only defined (but not called) before the "finish" message. It gets called from a different event handler, and that event happens later when the "keyup" event handler has already finished.