开发者

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:

  1. when a function is called I want to change the color of a DIV and then 1/2 second later I would like to change it back
  2. at the same time as (1) I would like to make an Ajax call. The call typically takes one second

In other words I would like step 1 and step 2 to start at the same time.

My knowledge of java开发者_运维问答script is pretty basic. Is this kind of thing possible? How about if I use jQuery, would that make it easier?


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
});


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

});


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜