Is it possible to have two function calls in a onclick? I tried doing something like:
onclick="function1(); function2();"
Doing that it only executes the first function, but not the second. Anyway to have both in the onclick? It code be on the client side or in the code behind in C#.
Thanks!
I'd say either function1 or function2 is undefined, or function1 is throwing an exception, or (with respect) you're simply wrong that both of them don't get called. In the normal case, both will be called (proof).
That's not to say it's a good idea. You'd be much better off defining a third function that calls the other two, or even better using DOM2 handlers and doing away with onclick entirely.
That should work. You may have an error in function1() which causes everything after it to not be executed.
That should be fine unless you have an error in one of your functions. However, I encourage other developers to have one function that calls both functions, then call it in your onclick event.
function function3()
{
function1();
function2();
}
... onclick="function3();"
Related
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.
I have a simple resizable div (achieved with jQuery's resizable) and I'm handling the resize event with a function.
So, let's say that's my code:
var a = ...
$(div).resizable({
options go here...
resize: function(e, ui){
make some operations with a
...
...
keep making operations with a
...
...
ok, we're done
}
})
Now, let's say the resize callback is called a lot of times in a short period of time. How will javascript handle that? Will callbacks overlap the use of "a"? (Note that "a" is a global var!).
Am I safe with this code or there might be a conflict of some kind?
Regards
If you're asking about thread safety, JavaScript is single-threaded. A function like that can only be run one at a time, regardless of how often it's called.
So you should be safe.
JavaScript is single-threaded so the function calls can't "overlap". If you trigger the event multiple times then the function is executed entirely (minus any asynchronous functions it may call) in response to the first triggering, before it's executed again to handle the subsequent triggers.
However, changes to a in one call will still have been made when the function is executed again, so if it relies on the value of a you may run into problems - it comes down to exactly what that function is doing with the variable.
This is a newbie question: I have a pre-existing function that I would like to have call another function when it is finished, however, it does not accept a callback nor of course call one. I can modify this code to accept and call a function however this got me thinking about whether JavaScript supports doing this ... I would think it does but I've never had reason to find this out, I'm assuming it's necessary when working with libraries where we cannot change the code to our liking. Thanks.
The only time you need a callback is when you are doing something asynchronous, such as:
making an HTTP request (and waiting for a response)
animating something, one frame every time period until it is done
waiting for the user to click a button
All of these are considered "done" when something happens, but there is no generic way to determine when the something has happened. You need something custom for each one.
If you aren't waiting for something, then you can just call one function after the other (foo();bar();) and not need to fiddle around with callbacks.
So…
It might be possible to do what you want, but we can't tell you a generic way to achieve it.
This is a bit of a hack, and i'm sure there's tidier ways to do this with polymorphism, but you can treat the function as a variable and re-assign it somewhat:
Say you start with this function:
function originalFunctionName()
{
// do something
}
you can assign the existing function to a new name:
var backupOfOriginal = originalFunction;
then you can define a new function over the original name:
var originalFunctionName = function()
{
// do something else
// call backup function
backupOfOriginal();
}
then if you call the original function name:
originalFunctionName();
all the code will execute.
You can always create a new function which calls that function and provides you with opportunities to do something else before and after it is called. Underscore.js provides .wrap() to do exactly that sort of thing and return you a function you can call instead of the first function.
That just gives you a new function to call instead of your original function, if you want every spot that called the original function to get the new behavior instead, you could take advantage of JavaScript's prototypal inheritance to replace the original function with your new version of it.
Create a wrapper function that calls the original function, then one you pass in.
If the original function is an Ajax call and you're trying to replace one of its handlers, that's a different issue, though you might be able to use jQuery's $.when(original).then(function () { ... }) depending on your actual needs.
I want to call fillContent then later called beginEditingQuestion
fillContent(cid, "questions");
beginEditingQuestion(qid);
The problem is that I can't rung beginEfitingQuestion until all the ajax in fillContent is done. Is there an elegant way to delay the code? The only idea I can think of is to make a totally new function fillContentAndBeginEditingQuestion where I copy and paste fillContent into the new function and in the final ajax call add in beginEditingQuestion. This doesn't seem very elegant to me, I want to reuse fillContent in other contexts. What should I do?
You can make fillContent take a callback parameter, and have it call the callback when it's done. Basically, you'd just add callback (); into the body of fillContent at the very end. In this way, you'd write something like this, and have the passed function executed at the end:
fillContent (cid, "questions", function () { beginEditingQuestion (qid); });
I don't think you want to "slow", rather you want to wait for something to complete before the next piece of work is begun.
A pattern for this, used in many languages, is to use Events.
Conceptually:
You register an interest in a "DoneFillingContent" event, saying please call beginEditingQueue() when the event arrives.
fillContent has the repsonsibility of emiting an event to all interested parties. He doesn't realise what beginEditingQueue() does, it just a piece of work to be done on completion.
In the simplest version of the pattern, you just allow one callback function.
It sounds like you need to change "fillContent" so that one of its parameters is a callback function that is invoked when the AJAX returns.
I know there is a method like this :
setTimeout("functionA();",1250);
That can delay my process, but the problem is , the functionA have some value to return. When I use this way, it is not get me back the functionA return value:
this.sth = setTimeout("functionA();",1250);
I means, this.sth is not the result I want.
You should make a functionB() that does this:
function functionB() {
this.sth = functionA();
// do things with the returned value
}
You could do:
setTimeout(functionA(functionB()), 1250);
and define functionB as:
function functionB(resultFromA) {
}
and functionA would look like:
functionA(callback) {
// do something useful
callback(result);
}
setTimeout is an asynchronous operation. This means that functionA gets run after the timeout but the rest of the script keeps running. It's a common mistake new javascript programmers make to think the script will be pausing when causing this.
If you goal is to make the script pause your better off using a while loop or for loop with dates. This is probably a bad idea though. A scrip that pauses can do weird things to browsers including making the whole browser pause while it runs. That includes all the tabs. This is probably not what you want. The better bet is to do like Garret mentioned and make it so that the operation works asynchronously but still accomplishes what you wanted.
i've seen solutions to this using for loops with thousands/millions of iterations. However be warned this can make the browser unresponsive if used incorrectly.