1

if i do:

method();
method();

both calls will run in parallel (at same time)

i just would like to make the second method(); wait until the first method(); is finished before to start, and do it dynamically cause i can't know how many times i will launch method(); at same time .

Is it possible?

just for example, those runs at same time as i can see... http://jsfiddle.net/Lcgb8/

15
  • Javascript does not support multithreading. Are you talking about AJAX? If so, use promises. Commented Aug 18, 2013 at 19:34
  • if you do what you describe in your code without using (fileReader,Xhr,Canvas or whatever is async) it will do it sequentially.your example executes sequentially. Commented Aug 18, 2013 at 19:54
  • @cocco indeed i need some tip to queue or stuffs like that, cause they are sync methods Commented Aug 18, 2013 at 19:54
  • so you want to wait until the next function executes? Commented Aug 18, 2013 at 19:56
  • yep exactly @cocco the next has to wait until the previous is fully executed Commented Aug 18, 2013 at 19:57

5 Answers 5

2

You could use then if you return a Deferred.

E.g.

function method() {
    var d = $.Deferred();

    //do something async
    setTimeout(function () {
        d.resolve('some data'); //inform listeners that the process is completed
    }, 2000);

    return d; //return the deferred object
}

Then you could do:

method().then(method).then(method).then(method);

Note that the return value of each call will be passed as first argument to the next call, respectively.

EDIT: Here's an example on how you could queue the async operations dynamically.

FIDDLE

function changeColorAsync(color) {
    var d = $.Deferred();

    setTimeout(function () {
        $('body').css('background', color);

        d.resolve();

    }, 4000);

    return d;
}

$(function () {
    $('#color-form').on('submit', function (e) {
        var color = $(this).find(':checked').val(), d;

        d = d? 
            d.then(changeColorAsync.bind(this, color)) : 
            changeColorAsync(color);

        return false;
    });
});
Sign up to request clarification or add additional context in comments.

6 Comments

the problem is that i can't now how many time i will call method(); cause method() is called after a websocket received data
this is an example, where _data is returned from a websocket randomly jsfiddle.net/Lcgb8
@plax i do not have this var colors = ['red', 'blue', 'yellow'] since colors are returned from a webscoket randomly each random seconds
@sbaaaang, I don't see the problem? var something = socketresult;, then you process the result if it's a collection. If it's not it's even easier you simply have to keep a reference to the last deferred, let it be d, and you could just do d.then(...)
@sbaaaang Always keep a reference to the last deferred and it will become your entry point to queue the next operation. For first operation you do var d = d? d.then(method) : method();, then subsequent operations are just d = d.then(...). It will effectively queue all async operations.
|
1

Here is a sequentially animation using transitionend

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>animation</title>
<style>
div{
width:50px;height:50px;background-color:#093;
-webkit-transition:all 300ms ease;
}
div.move{-webkit-transform:translate3d(200px,0,0);}/*GPU HW acceleration*/
</style>
<script>
(function(W){
 var D,d,L,c=0;
 function init(){
  D=W.document;d=D.getElementsByTagName('div');L=d.length;var l=d.length;
  while(l--){d[l].addEventListener('transitionend',next,false)}
  next();
 }
 function next(){
  d[c].classList[(d[c].className=='move'?'remove':'add')]('move');
  c++;c=(c==L?0:c);
 }
 W.addEventListener('load',init,false);
})(window)
</script>
</head>
<body><div></div><div></div><div></div><div></div></body>
</html>

it had little error fixed now..

supports infinite div's and it's infinite loop using low resources. =)

your method() would be my next()

if someone want's to jsfiddle it... i don't use that.

ps.: pure javascript (no jquery) + css3 (with -webkit prefix);

example

http://jsfiddle.net/4eujG/

Comments

0

Have a look at jQuery.queue().

5 Comments

will i ask too much if i ask you a little example :P ? please
@sbaaaang: What about the example on the documentation page that Matthias linked to?
i sincerilly can't understand how to use it from the example, since it uses a strange "fx" via queue that i don't know what is :/
It's just a name of the queue. Like "Maria", "Lucia", "fx" ;)
@TheFrost come on couldn't be faster and better to put here an example please? i'm troubling with that damn queue but i can't understand very well :(
0

Using callback:

var test = function (letter, callback) {
    console.log(letter);

    if (typeof callback !== 'undefined') {
        callback();
    }
};

Now you can run it:

test('a', function () {
    test('b', function () {
        test('c')
    });
});

The result in console is:

a
b
c

Is it helpful to you?

2 Comments

thanks but it's not helpfull cause to run your code you need to know how many methods() you'll going to launch, i can't know it should be dynamically queued if possible :P
function method(a){console.log(a)};method('a');method('b');method('c');does the same.
-1
     $( "div" ).promise().done(function() {
     $( "p" ).append( " Finished! " );
     });

Hope this example must have cleared your query

LIVE DEMO

Javascript, and most other languages, run code sequentially.

Therefore, they will not both run at the same time.

In fact, it is not possible to run two different pieces of Javascript code at the same time. However, in many other languages, it is possible using threads.

However, if they make AJAX calls, the corresponding server-side code called by both functions will run simultaneously. To prevent that, you'll need to make the first function accept a callback parameter and pass it the second function.

2 Comments

i need to do it dinamycally i guess queuing is the only solution
or create sort of methods array then launch it one by one but the problem remains, cause i need to be sure the previous method has finished before to launch the next one

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.