asynchronous - How to force Sequential Javascript Execution? -
I have found complex answers related to classes, event handlers and callbacks (which are somewhat shy to me). I think callbacks can be useful, but I can not apply it in the simplest context. See this example:
& lt; Html & gt; & Lt; Top & gt; & Lt; Script type = "text / javascript" & gt; Function myfunction () {longfunctionfirst (); Shortfunctionsecond (); } Function long before () {setTimeout ('Warning ("Firstly finished");', 3000); } Function ShortfunctionSend () {setTimeout ('Warning ("Second Function Ended");', 200); } & Lt; / Script & gt; & Lt; / Head & gt; & Lt; Body & gt; & Lt; A href = "#" onclick = "javascript: myfunction (); return back;" & Gt; Call my function & lt; / A & gt; & Lt; / Body & gt; & Lt; / Html & gt;
In this, the second function is completed before the first function;
--- Edit ---
This is because the easiest way to compel another function to delay second performance (or what is it?) There was a garbage example but for David Headuland, I see with this new example that it is really synchronous (as well as crashing my browser in the testing process!):
& Lt; Html & gt; & Lt; Top & gt; & Lt; Script type = "text / javascript" & gt; Function myfunction () {longfunctionfirst (); Shortfunctionsecond (); } Function longfunctionfirst () {var j = 10000; For (var i = 0; i & lt; j; i ++) {document.body.inner html = i; } Warning ("First Function Ended"); } Function shortfonesecond () {var j = 10; For (var i = 0; i & lt; j; i ++) {document.body.inner html = i; } Alert ("End second function"); } & Lt; / Script & gt; & Lt; / Head & gt; & Lt; Body & gt; & Lt; A href = "#" onclick = "javascript: myfunction (); return back;" & Gt; Call my function & lt; / A & gt; & Lt; / Body & gt; & Lt; / Html & gt;
As with my real problem, I have to post a different question with jQuery and IE if I can not get anywhere!
OK, setTimeout
, according to its definition, will not stop the thread . It is desirable, because if this happens, it would freeze the whole UI for the time it was waiting. If you really need to use setTimeout
, you should use callback functions:
function myfunction () {longfunctionfirst (shortfunctionsecond); } Function longfinfff (callback) {setTimeout (function () {warning ('first function ended'); if (callback == 'function') callback ();}, 3000); }; Function shortfonesecond () {setTimeout ('warning ("second function ended");', 200); };
If you're not using setTimeout
, but there are still functions that are executed for a very long time, and Using setTimeout
to simulate this, then your work will be will actually synchronous, and you will not have this problem at all. It should be noted, however, that the AJAX requests are asynchronous, and as the setTimeout
will not suppress the UI thread until it is complete. Along with setTimeout
, with AJAX, you have to work with callback.
Comments
Post a Comment