I have something like this:
function doSomething() {
var obj = $('somediv');
...
waitAndDoSomethingElse(obj);
...
$('somediv').show();
...
}
function waitAndDoSomethingElse(obj) {
obj.fadeIn();
....
}
I want doSomething() to pause... execute waitAndDoSomethingElse() and then continue...
Any ideas?
Thank you
EDIT:
I'll try to explain better, sorry if my question was confused...
function showSomething() {
var whatToShow = $('#div');
doSomethingElse();
whatToShow.fadeIn('slow');
}
function doSomethingElse() {
$('#someDiv').appendTo($('#someOtherDiv'));
$('#somethingElse').fadeIn('slow');
...
}
In this example whatToShow.fadeIn will fire without waiting for doSomethingElse to end...
Use the animation callbacks. All the animations have them as the last arg.
See here for the fadeIn docs.
$('#someElement').fadeIn('slow', callbackFn);
function callbackFn(){
//executed after the fadeIn is complete
}
If you are not using the animation helpers then you can use the same methodology and pass callback functions to other functions which can choose when to call the callback.
var callbackFn = function(){ //do something };
doSomething( callbackFn )
function doSomething( callback ){
doOtherStuff();
//call the callback
callback && callback()
}
Another option is to use window.setTimeout to fire a function after x milliseconds.
Do this
function doSomething() {
var obj = $('somediv');
...
waitAndDoSomethingElse(obj);
}
function waitAndDoSomethingElse(obj) {
obj.fadeIn();
// if you want a pause here you can also add the next call in a setTimeout()
$('somediv').show(); // this call is executed only after
}
Related
how to run next function after first done with setInterval?
for example:
step1();
step2();
setInterval(step1, 1000).done(function() {
setInterval(step2, 1000).done( /* next step */);
});
please help me with solution!
Edit: This is an old answer. Now you can achieve this using promises also but the code will be slightly different.
If you don't want to use a promise you can use a simple flag to achieve such a thing. Please see example below:
var flag = true;
function step1() {
console.log('title');
}
function step2() {
console.log('subtitle');
}
function wrapper() {
if(flag) {
step1();
} else {
step2();
}
flag = !flag;
}
setInterval(wrapper, 30000);
If you want to chain functions on completion you can use callback functions.
Example:
function first(callback) {
console.log('Running first');
if (callback) {
callback();
}
}
function second() {
console.log('Running second function');
}
first(second);
The first function checks if a callback is used and then runs it. If there is no callback function nothing happens. You can chain functions this way.
You can also use anonymous functions.
first(function () {
console.log('This function that will run after the first one);
});
If you use setTimeout() you can't be sure whether the previous function has completed. A better way would be to use promises.
Understanding Promises
I hope I understood your question right. Good luck!
First of all setInterval can not be done by itself, it will fire infinitely if you not clear it with clearInterval.
But if you have some async action inside your function and whant to wait for it and then call another function you may just promisify it like Avraam Mavridis suggested.
function step1() {
var deferred = $.Deferred();
setTimeout(function () {
alert('I am step 1');
deferred.resolve();
}, 1000);
return deferred.promise();
}
function step2() {
alert('I am step 2');
}
step1().done(step2);
JsFiddle
I want to call a function that is in another function.
example for the functions:
function funcOne() {
function funcTwo() { // i want to call to this function
//do something
}
}
I need to call to funcTwo function, when I click on a button which is outside of these two functions
how can i do it?
No, You can't call unless you return that function.
Function2 is private to function1.
you use
function funcOne() {
return {
funcTwo :function() { // i want to call to this function
//do something
}
}
}
EDIT: Structuring code
function funcOne() {
var funcTwo = function() { // private function
//do something
}
return {
funcTwo : funcTwo
}
}
Now you can call it as:
funcOne().funcTwo()
As you have it defined in your example, you can't. funcTwo is scoped inside of funcOne, so it can only be called from inside funcOne. You can assign funcTwo to a variable that is scoped outside of funcOne and that would work:
var funcRef;
function funcOne() {
funcRef = function funcTwo() {
}
}
In this case, funcRef would hold a reference and could be used, but that reference is only set once funcOne has been executed.
Reading some Douglas Crockford may help you understand...
Try recoding as:
function funcOne() {
this.funcTwo = function() {
}
}
I think you'd have to declare an instance of a funcOne object and then call the funcTwo method of that object. I'm a bit busy at the moment so I can't refine this answer at the moment.
It is not possible as the second function will be created just when the first function is called. it is not existent prior to that.
You would have to define it outside the first function like so:
function funcOne() {
}
function funcTwo() { // i want to call to this function
//do something
}
Or you could also call the first function and return the second function like this:
function funcOne() {
function funcTwo() { // i want to call to this function
//do something
}
return functTwo;
}
And then call it like this:
var f = funcOne();
f();
I'm trying to get setTimeout to re-run the function it's inside after 15 seconds, it's not waiting 15 seconds and just doing it in a constant loop.
Here's my current code
function checkSession(x) {
http.abort();
http.open("GET", siteURL+"processes/ajax.php?call=check_session&string="+x+"&new="+Math.random(), true);
http.onreadystatechange = function() {
if(http.readyState == 4) {
if(http.responseText == true) {
updateSession(x);
} else {
setTimeout(checkSession(x),15000);
}
}
}
http.send(null);
}
I don't see any problems in the code itself, the only thing wrong is that it's just doing a constant loop without waiting the "15000" miliseconds.
change the setTimeout call to:
setTimeout(function(){checkSession(x)},15000);
As you have it now, checkSession is called immediately and then passed as an argument to setTimeout. Wrapping it inside the function allows for the call to be deferred.
Your explanation:
The function is like this: setTimeout( function, delay );
Your method call was not setting an anonymous function or reference to a function as the function argument.
Wrong: setTimeout(checkSession(x),15000);
Reason: checkSession(x) is a function call, not a reference to a function or anonymous function
Right: setTimeout(function() {checkSession(x) },15000);
Reason: the function call is now wrapped as an anonymous function in place and the function argument is set for the setTimeout( function, delay ) method.
Hope that helps to clear it up for you!
So let's say I'm calling a function like so:
some_function('pages',{attr1: 1, attr2: 2},function(){
alert('the function is ready!');
}
Now how do I set up the "some_function()" function in order to return to the caller that it is ready and make the alert go off?
Thanks :)
I think you mean callbacks.
Maybe something like this:
function some_function(param1, param2, callback) {
// normal code here...
if ( typeof callback === 'function' ) { // make sure it is a function or it will throw an error
callback();
}
}
Usage:
some_function("hi", "hello", function () {
alert("Done!");
});
/* This will do whatever your function needs to do and then,
when it is finished, alert "Done!" */
Note: Put your return after the if clause.
Do you mean something like this?
function some_function(type, options, callback) {
if (some_condition) {
callback();
}
}
Assuming the signature for some_function looks like this:
function some_function(name, data, callback)
You just need to call callback when you're ready to.
function some_function(name, data, callback){
// do whatever
if(typeof callback === 'function'){
callback(); // call when ready
}
}
I am not writing a plugin. I am just looking for a simple clean way to let myself know when a certain function has finished executing ajax calls or whatever.
So I have this:
function doSomething() {
...
getCauses("", query, function () {
alert('test');
});
...
}
function getCauses(value, query) {
//do stuff...
}
Of course the alert never happens. I have a $.ajax call inside getCauses and would like to alert or do some action after getCauses finishes executing and then running the line of code from where the function was called.
Ideas? Thanks.
You first need to add the parameter to getCauses:
function getCauses(value, query, callback) {
}
Then, inside of your $.ajax call, call the callback parameter in your AJAX completion callback:
$.ajax({
// ...
complete: function() {
// Your completion code
callback();
}
});
You're passing your callback function but not executing it.
function doSomething() {
...
getCauses("", query, function () {
alert('test');
});
...
}
function getCauses(value, query, callback) {
//do stuff...
//stuff is done
callback();
}
Just using a bit of javascript trickery, here's an implementation that will allow you to implement some default functionality, in the case that no callback is defined. This would be great if 99% of the time you want a generic callback, and then you simply want to customize it in a few places.
var my_callback = function() {
alert('I am coming from the custom callback!');
}
var special_function(string_1, callback) {
(callback || function() {
// Default actions here
alert('I am coming from the generic callback');
})();
}
// This will alert "I am coming from the custom callback!"
special_function("Some text here", my_callback);
// This will alert "I am coming from the generic callback"
special_function("Some text here");
// This will do nothing
special_function("Some text here", function() {});
Cheers!