how to make sure one javascript function get caled after another function - javascript

I am new to javascript and don't know whether its using stack for keeping trace of function calling .
This is the code i got stuck with
function bounce(nIdx,bMulti)
{
idDivread.style.display='';
initBounceMgr();
cBounceMgr.bounce(document.all.KnlTbl.rows[nIdx].cells[0].procName,bMulti);
readKill();
}
function readKill()
{
idDivread.style.display='none';
}
This bounce function is called by onclick event and i want to show a div as it has image of wait symbol. And this is working but as i want to remove this wait symbol after function call is done i applied this readKill function. But then that image is not coming at all.
Seems that this function get called before these two functions.
What to do to make sure that readkill function get executed after this two function.

They are being called in the order you would expect. The problem probably comes from the fact that if bounce is an animation or similar it probably returns immediately and does the animation asynchronously. So what it is in fact doing is showing the div, starting the bounce, then hiding the div and in the hidden div doing your bounce animation.
Usually methods that run like this will accept a callback parameter. That is a method that is called after they have finished doing what they want. In this case you would pass readKill in as the callback function instead of calling it directly.
I'm not sure what the cBounceMgr object is though so it is impossible to give you exact syntax to use.

Related

Dynamically modifying function call according to context

I have a web page which has four tabs at the top. Clicking one of the tabs displays the appropriate page beneath. The tab selection and display is controlled by a js/jQuery function I've called 'changeTab'. Nothing uusual there.
I want to set up a (different) JS function for each tab, to run when that tab is displayed, similar to the way jQuery 'document.ready' works when the main page itself is loaded. I can put a function call at the bottom of my 'changeTab' function, such as 'tabLoaded()'. But that obviously only calls the same one function each time.
I can name the functions 'tab_1_Loaded', 'tab_2_Loaded' etc. ,but then I need some way of dynamically modifying the function call so that the number of the tab is included (I already have the tab number, I just need to work out how to insert it into the function call).
What I am hoping for is a function call like:
tab_[insert tabNum dynamiclly here]_Loaded();
Is that possible in a few lines of code?
I have read articles on Stackoverflow, but they seem do address a different problem of creating (new?) functions with a dynamically derived name. I can be quite clear what my functions are called. I need a dynamically derived call. I suspect it may be possible with 'eval' but my reading also suggests eval is to be avoided, so I've not pursued it.
My fall-back is a series of conditionals:
if(tabNum == 1) tab_1_Loaded();
if(tabNum == 2) tab_2_Loaded();
etc.
but it seems inelegant (though simple) and it certainly works in this case where the number of possibilities is small. Is there a better way that's also simple?
LATER: I've subsequently realised there's an additional complication for the particular page/tabs I'm working on right now, (though it won't apply to the entire site). This page is for on-line booking. The first tab is the booking form (visitor enters dates, number of people). The second and subsequent tabs aren't populated until the visitor clicks 'Next' and moves on to the next stage. Consequently any function call in the 'changeTabs' function is made before the contents of the tab have actually loaded, so it does't work.
To deal with that I'm going to put the call into a script at the bottom of each tab contents. I expect there are more elegant ways of doing it, but it's only one line of code, whereas all the offered solutions are actually more verbose (and harder for me to understand). I will probably still need the call from 'changeTab' to cope with the visitor flicking through the tabs before finalising the booking.
When press the tab, the call back function will always be invoked, no matter what how many call back functions all will be invoked. You cannot conditionally invoke a callback function from a key press. Ideal way to implement this would be
i) Have a single call back function for the tab event
ii) Identify the id of the element, that is currently on focus when tab is pressed inside that call back function
iii) Add conditions based on that element on focus to have your logic of functions for respective elements
Yes it's possible to do what you're asking. All functions and variables declared with global scope are methods and properties of the window object, so you can build the name of the your function as a string and reference it via bracket notation.
So assuming you have tabNumber already stored in a variable:
var functionName = "tab_"+tabNumber+"_Loaded";
window[functionName]();
(See https://codepen.io/slynagh/pen/MMVEoE)
But a better approach would be to use callback functions or else use one tab_Loaded() function which accepts the tabNumber as a parameter, eg:
function tab_Loaded(tabNumber){
if(tabNumber === 1) { do something }
else if(tabNumber === 2 ) {do something else}
//etc
}

JavaScript not starting function

I have search for some sort of way to do this, but i can't make it work. It may seem simple but i don't know much about javascript so I have found very little information on the problem and I don't know were is the error at so i'll just briefly explain what it's supposed to do. First here is my code:
function showI(a){
$("#show").fadeIn();
$("#show .load").fadeIn();
$("#show").load("ajax/showi.php?id="+a,$("#show .load").fadeOut("fast"))
}
$('.List-item').on('click touchstart',function(){
var id=$(this).attr("id").split("list-").join();
showI(id);
})
So there's like a button with the class list-item which when click should open a new window with the showI function, but it doesn't(I used before the attribute onClick, but it didn't work on mobile so I changed it to .on(click touchstart))
Any help would be appreciate. (Don't know if this is replicated because i can't find a word to describe the problem)
This line:
$("#show").load("ajax/showi.php?id="+a,$("#show .load").fadeOut("fast"))
calls $("#show .load").fadeOut("fast") and then passes its return value into load as a second argument, exactly the way foo(bar()) calls bar and then passes its return value into foo.
If you're looking for a completion callback, you need to wrap that in a function:
$("#show").load("ajax/showi.php?id="+a, function() {
$("#show .load").fadeOut("fast");
});

In JavaScript, is there a universal approach to known when asynchronous actions are finished?

In my work, I frequently encounter following situation:
Situation A:
I need to make multiple ajax calls in one function to retrieve data from server. So I have to make callback functions and define a counter to determine whether all the calls get done.
For example , in each of the sub-functions ( with ajax calls), at the end of the done, I would callback to check the counter's value.
ajax.done(funciton(jsResponse){
.......
base.ajaxLoaded++;
base.dataLoaded();
});
then in base function, I check the value:
dataLoaded: function()
{
var _this = this;
if (_this.ajaxLoaded == 4)
{
// all loaded
_self.render();
_this.afterInit();
}
}
Situation B:
There is a modal pop up triggered by the completion of an animation. So, I have following choices:
1) make a setTimeout function with a timer ( estimated the length of animation)
something like:
setTimeout(function(){
window.MYAPP.triggerMymodal();
},1000);
2) set up a interval function to check repeatedly whether a flag's value has changed and I embedded this flag into the animation finish function, to set it true or false.
if this flag true then make my next move and kills this interval.
3) change animation div attributes and check it use interval function.
Situation C:
Use window.print() function to print something and then need detect when it's finish. This has been asked by myself in this:
how to detect window.print() finish
My Question:
In JavaScript, is there a certain kind of method or Technic to deal with those functions which have unknown execution time? or this is just a case by case thing based on what technology you use?
Yes, the modern approach to dealing with this is called Promises. Various libraries implement the concept, which is basically that you can chain together groups of things that need to happen, either is parallel or serial, and then define success and failure outcomes for each of them.
It takes a bit of time to get your head around it but once you do the code is much more straightforward.

Execute just part of a method in JavaScript

I have a method that could potentially do both parts of the greater task at hand. Basically I have two buttons one button uses the entire method and returns a result at the bottom of the method. Now, my question is about the second button. The second button needs to do everything in that same method but only from line x of said method. Instead of writing a second method that repeats the same exact code from line x down of said method is there a way to jump over bits of code and only execute portions of a method in javascript? Or perhaps I am thinking about this all wrong?
Do two separate methods like this:
function a(){
//do first half of function
b();
}
function b(){
//do second half of function
}
2 ways,
split out the chunk that gets used twice into a separate method, and call from either within the first method, or from the other context directly.
add another argument to the method that expects a boolean value. The function then skips over the unneeded bits based on that value passed in. It can then be called differently from different contexts.
you can call String(yourfunc) to get code, then dynamically create second function by cutting only further lines, you can get array of lines by splitting by ('\n') then join array elements from place you want to begin and evaluate new function, code:
function split(bigfunc,line){
for(var small = String(bigfunc).split('\n'), i=line,n='',l=small.length;++i<l;)
n+=small[i];
return eval('(function(args){'+n+')'};
}
where args in last line you need to replace with args from original function, eventually you can assume args will be the same, then replace line with:
return eval('('+small[0]+n+')') if you're putting { after arguments of function like me or put +'{'+ between small[0] and n if you're putting { in new line.
it'll return new function with only code after line.
Dude, look how many lines of code will you save...
To be serious - it's overkill. I'm using dynamic code manipulation like this to dynamically create webworkers only with parts of code from primary thread and crafting blobs and urls to them in fly to reduce loading time. But it's way more serious purpose than just making code shorter, but...
at least it'll be soooo pro xD

window.setInterval - is it possible to have more than one? how?

I have created a slideshow widget, using jQuery.UI widgets that works with window.setInterval.
I am trying to have more than one slideshow in the same page and i get the following results:
If I try invoking the same widget for both of my divs with images:
$('#div1').slideshow();
$('#div2').slideshow();
none of them work;
I have cloned the definition of my widget and named it slideshowsmall
$('#div1').slideshow();
$('#div2').slideshowsmall();
and only the second one works.
my widget code is in this pastebin, but i really think the problem, at least in the second try, has to do with setInterval
Thanks
Having multiple setInterval() by itself cannot be causing problems. It is more likely to have something to do with the code it's executing (and your widget code being non-english makes it very hard to analize and comprehend).
setInterval() returns and integer ID of the "interval", so that you can later clearInterval(...) by passing this ID. This scenario was implemented exactly for multi-interval uses. More details on MDC
As per your widget code when setInterval calls the ChangeLeft/Right.. method the slideshowdiv variable always points to the last element on which slideShow is called. the reason for this is the way you are invoking change methods which is not adviceable.
Please use the below code to call your change method it should solve your problem. You will notice I am passing the slideshowdiv object to change methods.
this.options.timer = window.setInterval(function () {
ChangeImageLeft(velocidade, slideshowdiv);
}, intervalo);
Let me know if you need more info.

Categories

Resources