Can anyone explain me the execution process of functions in jquery - javascript

I have a small doubt on Execution cycle of function in jquery. I'm trying to do some stuff with js, And in my script I have one custom function that calls on click of a button. What happens is, when I call the function it will make some ajax call and assigns the result to a variable. According to my knowledge after the execution of the function next statement should execute. But here what happens is after function call before completing the function execution next statements are executing.
Structure of my script is :
var variable=false;
function myfunction(e){
.....
.....
$.ajax({});
.....
console.log('inside : '+variable);
}
$('#button').click(function(){
....
....
myfunction(n);
console.log('called : '+variable);
....
$.ajax({});
....
....
});
Console output:
Ajax call from the function;
called : false
Ajax call from called function;
inside : true
Can anyone explain this stuff....

it will heppen indeed like this just beacause your custom function is an Ajax Call not a normal code.
Ajax stands for Asynchronous Javascript and XML
So, the request processing occur smultanelously that is what for ajax is used.
that is the reason, why even before compelting your function execution , the next statements are being executed. ( asynchronously)
Hope this helps..
Note: What ever the code you put in the Call back function of the ajax , they will be executed only after ajax call is completed

this is the power of js callbacks!
the js callbacks will do things after, and callbacks will run when get response! But js will not wait for the callbacks excution to continue, the following functions will run! Async is the beauty of js.
so in your js file, you make a ajax call for something. while ajax's running, the console will not wait until ajax complete!
if you want to excute the ajax function sync, you may make a config in the params {async: false}, then the console will wait until the ajax func complete then excute!

The call to .ajax:
Assigns an event handler to run a function when a response to an HTTP request is received
Sends the HTTP request
The next line of code runs immediately for the same reason that a line of code immediately after $('foo').click(...); runs before the function you pass to click.

Related

javascript - Order of executing functions

I have some javascript functions being called on Document Ready:
fogFields();
getLoS();
getShips();
startGame();
getNextMove();
However, it is as though getNextMove() is being called first, most likely as all it does is an ajax call and alerts the result. All the other functions have more work, so, the first thing that happens on load is the getNextMove() alert, and in the background you can see that none of the other functions did their work. Until I click OK on the alert window, no results are shown. Can I make it so that until a function finishes, the next wont even start. Some functions call their own extra functions before they finish, and that works in order, but I cant do that with the whole code...
Given the code in your question, there is no way the call to getNextMove can be invoked before startGame has been exited, regardless of their contents.
It may be true that a function that has been scheduled asynchronously (via timeout, AJAX callback etc.) within startGame completes at any time before or after the invocation of getNextMove, but this is a separate issue. To resolve that issue we need to know more about the contents of the functions.
If the other functions have an AJAX call in them, then these AJAX calls most certainly take a callback argument, which is a function that gets executes, when the AJAX call has finshed. Now, if you want to execute your functions in a way, the one function starts when the AJAX call of the previous function finished, you can add an additional callback argument to your own functions, which will then be passed to the AJAX calls. This should illustrate what I mean:
function logFields(callback) {
ajaxCall(callback);
}
function getLoS(callback) {
ajaxCall(callback);
}
function getShips(callback) {
ajaxCall(callback);
}
function startGame(callback) {
ajaxCall(callback);
}
function getNextMove() {
}
fogFields(function(){
getLoS(function(){
getShips(function(){
startGame(function(){
getNextMove();
});
});
});
});
If all of your functions use a ajax call then just use promises.
Simply return it, for example:
function fogFields(){
return $.ajax();
};
and then just use .then:
fogFields().then(getLos());
more information about deffered object on jquery doc page if you use it.
Or implementation in pure javascript you can find here and more theory here.
or another option, which I will not recommend you is to set async param in $.ajax call to false. Again it's for case you use jQuery.

waiting a function to complete

I have 2 functions. The second one is faster than the first one,how could the function wait to complete first one's work?
function1(); // slow
function2(); // fast
JavaScript is imperative and single-threaded, it just works like this. function2() won't start until function1() finishes.
If by slow you mean calling asynchronously some external service via AJAX, then we're talking. function1() must provide some sort of callback so that when asynchronous request finishes, function2() is called:
function1(function2);
The implementation is trivial, e.g. using jQuery:
function function1(callback) {
$.ajax({url: 'some-url'}).done(callback);
}
If functions are to be called asynchronously, aside from the obvious callback approach, their sequencing could be based on the events framework. You could add an event listener with function1 as a handler, and trigger that event within function2.
You must be using some AJAX request. So, after ajax complete call callback function like:
function1 = new function(callback) {
$.ajax({...}).done(callback());
}
function1(function2);
If your calling one function after the other then it will finish the first either it may be slow or fast.

Possible Javascript scope issue

I'm sort of a noob with this so please forgive me :)
I can't get this one part of the function to update the variable. Could anyone possibly take a look a see what I'm doing wrong?
http://pastie.org/private/zfnv8v2astglabluo89ta
From line 142 thru 172 I'm not getting any results in the end. I've tested inside that function to make sure it is actually returning data, but the "body" variable is passing back up after line 172. So if I look at my generated HTML on the page, it simply looks the function skips from 140 to 174.
Thanks for any feedback!!
Your $.get is asynchronous. That means it will finish sometime AFTER the rest of the code, thus you won't see it's effect on the body variable inside that function. Instead, it's success callback function will be called long after this function has already finished.
To chain multiple asynchronous ajax calls like you have here, you can't just use normal sequential programming because asynchronous ajax calls aren't sequential. The network request is sent, then your javascript continues executing and SOMETIME LATER when the response arrives, the success handler is called and is executed.
To run sequential ajax calls like you have, you have to nest the work inside the success handler so that the ONLY code that uses the response is actually in the success handler. In pseudo-code, it looks like this:
$.get(..., function(data) {
// operate on the results only in here
// a second ajax function that uses the data from the first
// or adds onto the data from the first
$.get(..., function(data) {
// now finally, you have all the data
// so you can continue on with your logic here
});
// DO NOT PUT ANYTHING HERE that uses the responses from the ajax calls
// because that data will not yet be available here
});
You cannot do what you're doing which is like this:
var myVariable;
$.get(..., function(data) {
// add something to myVariable
});
$.get(..., function(data) {
// add something to myVariable
});
$.get(..., function(data) {
// add something to myVariable
});
// do something with myVariable
None of those ajax calls will have completed before the end of your function. You have to follow a design pattern like in my first example.
For more advanced tools, one can always use jQuery deferreds which are just a different way of defining code to run after an ajax call is done. It looks a little more like sequential programming even though it's really just scheduling code to run the same way my first code example does.
Function 8 will be invoke after line 174-180. You must put code from 174-180 line to the end of function

How Does AJAX work

I have this call :
// some code;
myAjaxCall(
function abcd() {};
);
// more code
Can the more code and abcd executing in the same thread or different thread. I know it is asynchronous.
Assuming myAjaxCall is an ajax wrapper, and the first argument is the complete callback, the answer is "more code" will run before abcd function. But I'd need to see myAjaxCall function to know what is really going on.
Remember, the complete callback happens when ajax retruns. "more code" executes in the normal execution path.
The AJAX request is asynchronous, but the Javascript code is synchronous and single threaded.
The code following the AJAX call will complete before the abcd function can run. The event that occurs when the response arrives can't be handled until the code exits and returns control to the browser.

Javascript: Trigger action on function exit

Is there a way to listen for a javascript function to exit? A trigger that could be setup when a function has completed?
I am attempting to use a user interface obfuscation technique (BlockUI) while an AJAX object is retrieving data from the DB, but the function doesn't necessarily execute last, even if you put it at the end of the function call.
Example:
function doStuff() {
blockUI();
ajaxCall();
unblockUI();
};
Is there a way for doStuff to listen for ajaxCall to complete, before firing the unBlockUI? As it is, it processes the function linearly, calling each object in order, then a separate thread is spawned to complete each one. So, though my AJAX call might take 10-15 seconds to complete, I am only blocking the user for just a split-second, due to the linear execution of the function.
There are less elegant ways around this...putting a loop to end only when a return value set by the AJAX function is set to true, or something of that nature. But that seems unnecessarily complicated and inefficient.
However you're accomplishing your Ajax routines, what you need is a "callback" function that will run once it's complete:
function ajaxCall(callback){
//do ajax stuff...
callback();
}
Then:
function doStuff(){
blockUI();
ajaxCall(unblockUI);
}
Your AJAX call should specify a callback function. You can call the unblockUI from within the callback.
SAJAX is a simple AJAX library that has more help on how to do AJAX calls.
There's also another post that describes what you're looking for.
You can do a synchronous xhr. This would cause the entire UI block for the duration of the call (no matter how long it might take).
You need to redesign your program flow to be compatible with asynchronus flow, like specifying a callback function to be called after the response is processed. Check out how Prototype or JQuery or ... accomplishes this.
The answer is simple, you have to call unblockUI() when your ajax request returns the result, using jQuery you can do it like this:
function doStuff(){
blockUI();
jQuery.ajax({
url: "example.com",
type: "POST", //you can use GET or POST
success: function(){
unblockUI();
}
});
}
It sounds to me that you want the user to wait while info is being fetched from the db. What I do when I make an Ajax call for some info from the database is to display an animated gif that says "getting it..." - it flashes continually until the info is retrieved and displayed in the webpage. When the info is displayed, the animated gif is turned off/hidden and the focus is moved to the new info being displayed. The animated gif lets the user know that something is happening.

Categories

Resources