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/

itsme
  • 48,972
  • 96
  • 224
  • 345
  • Javascript does not support multithreading. Are you talking about AJAX? If so, use promises. – SLaks Aug 18 '13 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. – cocco Aug 18 '13 at 19:54
  • @cocco indeed i need some tip to queue or stuffs like that, cause they are sync methods – itsme Aug 18 '13 at 19:54
  • so you want to wait until the next function executes? – cocco Aug 18 '13 at 19:56
  • yep exactly @cocco the next has to wait until the previous is fully executed – itsme Aug 18 '13 at 19:57
  • what does your function? like i said normal functions execute sequentially.. there must be something inyour function that breaks the sequence. in that case you could call the second function at the end of the first function (so inside & at the end of the first) and so on.. but that is not nice. if you tell us what breaks the sequence you could use different methods to execute it later.in that case the callbacks someone -- are the right answer. – cocco Aug 18 '13 at 20:02
  • I guess you need to modify your method and inside add a check at the end if it needs another call to itself.but with this two linesof code noone understand what you want. it's an animation? – cocco Aug 18 '13 at 20:08
  • if it's a css animation that breaks your sequence you can use the eventlistener 'transitionend'. – cocco Aug 18 '13 at 20:17
  • @cocco go ahead please :P any clue appriciated actually :P – itsme Aug 18 '13 at 20:17
  • i also thought to closures but uhmm don't know if i'm right – itsme Aug 18 '13 at 20:18
  • so it's an animation? – cocco Aug 18 '13 at 20:18
  • @cocco take this example http://jsfiddle.net/Lcgb8/ – itsme Aug 18 '13 at 20:21
  • but think that method(); is called dinamycally in my case – itsme Aug 18 '13 at 20:21
  • @sbaaaang Have a look at my solution. It's probably the easiest one if you can modify the way `method` is implemented. – plalx Aug 18 '13 at 20:23
  • @plalx check this http://jsfiddle.net/Lcgb8/ _data is returned from a websocket so i can't now how many times and when method() will be called, the jsfiddle is just to show what i'm doing after received _data from a webscoket in my case – itsme Aug 18 '13 at 20:24

5 Answers5

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;
    });
});
plalx
  • 42,889
  • 6
  • 74
  • 90
  • the problem is that i can't now how many time i will call method(); cause method() is called after a websocket received data – itsme Aug 18 '13 at 20:22
  • this is an example, where _data is returned from a websocket randomly http://jsfiddle.net/Lcgb8/ – itsme Aug 18 '13 at 20:23
  • @plax i do not have this **var colors = ['red', 'blue', 'yellow']** since colors are returned from a webscoket randomly each random seconds – itsme Aug 18 '13 at 20:47
  • @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(...)` – plalx Aug 18 '13 at 20:50
  • @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. – plalx Aug 18 '13 at 21:00
  • @sbaaaang I added an example of what I was trying to explain. – plalx Aug 19 '13 at 01:33
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/

cocco
  • 16,442
  • 7
  • 62
  • 77
0

Have a look at jQuery.queue().

Matthias Holdorf
  • 1,040
  • 1
  • 14
  • 19
  • will i ask too much if i ask you a little example :P ? please – itsme Aug 18 '13 at 19:32
  • 1
    @sbaaaang: What about the example on the documentation page that Matthias linked to? – RichieHindle Aug 18 '13 at 19:32
  • 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 :/ – itsme Aug 18 '13 at 19:43
  • It's just a name of the queue. Like "Maria", "Lucia", "fx" ;) – TheFrost Aug 18 '13 at 20:00
  • @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 :( – itsme Aug 18 '13 at 20:16
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?

TheFrost
  • 1,265
  • 2
  • 15
  • 29
  • 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 – itsme Aug 18 '13 at 20:12
  • function method(a){console.log(a)};method('a');method('b');method('c');does the same. – cocco Aug 18 '13 at 20:13
-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.

Community
  • 1
  • 1
Vaibs_Cool
  • 6,126
  • 5
  • 28
  • 61
  • i need to do it dinamycally i guess queuing is the only solution – itsme Aug 18 '13 at 19:53
  • 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 – itsme Aug 18 '13 at 19:58