Skip to content Skip to sidebar Skip to footer

Can I Do More Have Javascript Do Two Things At Once?

I have a strange need. I would like to do the following in javascript: when a function is called I want to change the color of a DIV and then 1/2 second later I would like to chan

Solution 1:

You can use jQuery and its function queue, to delay an action.

I forked wdm's version on jsFiddle, to change it to queue style, instead of setTimeout. In my own belief, this is a much cleaner and better way to achieve what you are looking for.

Here is the forked Demo

Here is the JavaScript code:

$('#change').click(function(e) {
    e.preventDefault();

    $('#a')
        .css('background-color', 'blue')
        .delay(500)
        .queue(function(next){
            $(this).css('background-color', 'red');
            next();
        });

    $.ajax({}); // do the ajax call here
});

Solution 2:

I created the first part for you. It sets the color to blue, then back to red a half second later (500 ms).

You can then add the code for the ajax request where I have the comment. The color change and ajax call will begin at the same time when the function is called.

Demo: http://jsfiddle.net/wdm954/H39XZ/1/

$('#change').click(function(e) {
    e.preventDefault();
    $('#a').css('background-color', 'blue');
    setTimeout(function() {
        $('#a').css('background-color', 'red');
    }, 500);

    // Insert ajax call here

});

Solution 3:

One important concept is that javascript is a single-thread thing. Only one thing really happen, no parallel tasks.

Here is a nice tutorial to get this point in details.

Now that doesn't mean javascript execution seems single-threaded for the final user. You've got plenty of tools with asynchronous ajax calls and timer-based events (like jQuery queues used in animation things) that will make the javascript jobs interlayed. This means pieces of jobs will be done step after step, and for several graphical zones, so you'll get the final impression they're done in parallel.

This is why @Shef answer is right, as well as @anirudh4444 one.

Solution 4:

The very purpose of AJAX is to make asynchronous calls. You could execute a function using the setTimeout() and setInterval() if you want them to execute at a later time.

Post a Comment for "Can I Do More Have Javascript Do Two Things At Once?"