简体   繁体   中英

JavaScript execution order - run this(), then that() when this() has finished?

If for example, I have some jQuery doing something simple like:

$("div").fadeIn('fast');
$("div").html('Foo');

That would fade in the div, and set its html to "Foo" whilst it's still fading in, whereas:

$("div").fadeIn('fast',function(){
   $("div").html('Foo');
});

Will only set the html to "Foo" after the div has completed fading in.

Is this sort of thing the way JavaScript works in general? So if I had:

//do something
var i = 42;
var foo = i/1;
//do something else
var bar = fooBar();

Will it start doing something else whilst it's still doing something, or will it wait patiently for do something to finish before it does something else?

JavaScript in general does not work like this, you're seeing the result of jQuery animations and callbacks. When you run something via setInterval() it happens outside the current thread, kicking in later ( .fadeIn() is an animation, they're on interval timers ).

So the second function you pass to .fadeIn() (or any .animate() function) is a callback , it executes this when it's done. Outside of intervals and timers though, your script will occur in order.

Even with intervals and timers it occurs in order, just not the order it appears in code, chronologically when things should happen they do (provided they finish in time and the main thread isn't waiting, even then they're in order , if not on time ).

Javascript is running in one thread in a browser, so things will run in sequence, one after the other. Timeouts and callbacks will wait if there is anything happening and will run to finish.

The only exception is Web Worker Threads , but they shouldn't affect the UI.

JavaScript is single threaded, it can only do one thing at a time, usually in order. The callback pattern just sticks a function behind a running script when invoked. It becomes more complicated when you start using the observer pattern (eventListeners).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM