Call a function after previous function is complete
Specify an anonymous callback, and make function1 accept it:
$('a.button').click(function(){
if (condition == 'true'){
function1(someVariable, function() {
function2(someOtherVariable);
});
}
else {
doThis(someVariable);
}
});
function function1(param, callback) {
...do stuff
callback();
}
How to make a function start only after another function fully completed in JavaScript?
To show the movement by pump()
as 2 steps, you'll have to give the UI time to redraw in between the 2 movements. Currently, it won't redraw until the end of the click
event, when k
and the circle are already at 8
.
You can give it that time with a brief setTimeout()
.
function pump(val) {
if (val == 6) {
setTimeout(function () {
alert("you get pumped");
k = 8;
var parent = document.getElementById('a' + k);
var circle = document.getElementById('crcl');
parent.appendChild(circle);
}, 10);
}
}
The delay doesn't have to be long; the alert()
will hold the user's attention while the circle shows on square 6.
Combined with your example:
var k = 0;document.getElementById("btn").addEventListener("click", function () {
var num = Math.floor(Math.random() * 100); num = num % 3; /*generate a random no between 0 to 2*/ num = num + 1; /*generate a random no between 1 to 3*/ //alert(num);/* check the no*/ document.getElementById("currnt-value").innerHTML = "you get" + num; k = k + num; var parent = document.getElementById('a' + k); var circle = document.getElementById('crcl'); parent.appendChild(circle); pump(k); demotive(k);});
function pump(val) { if (val == 6) { setTimeout(function () { alert("you get pumped"); k = 8; var parent = document.getElementById('a' + k); var circle = document.getElementById('crcl'); parent.appendChild(circle); }, 200); }}
function demotive(val) {
if (val == 7) { alert("oh..!!!you are demotived"); k = 3; var parent = document.getElementById('a' + k); var circle = document.getElementById('crcl'); parent.appendChild(circle); }}
html,body{ width:100%;height:100%; }
#board{ width:300px; height:300px; border:1px solid #000; }#one,#two,#three{ width:100%; height:100px; float:left; }.flag-point{ width:100px; float:left; height:100%; }#a8,#a2,#a4,#a6 { background-color:green; }
#crcl{ width:30px; height:30px; background-color:red; border:1px solid #000; border-radius:50%; }
<div id="crcl"> </div> <button id="btn">move circle</button><p id="currnt-value"></p>
<div id="board"> <div id="one"> <div id="a9" class="flag-point">9</div> <div id="a8" class="flag-point">8</div> <div id="a7" class="flag-point">7</div> </div> <div id="two"> <div id="a6" class="flag-point">6</div> <div id="a5" class="flag-point">5</div> <div id="a4" class="flag-point">4</div> </div> <div id="three"> <div id="a3" class="flag-point">3</div> <div id="a2" class="flag-point">2</div> <div id="a1" class="flag-point">1</div> </div></div>
Only start function when previous function has completed
It sounds like you're using a web framework, so maybe include the framework, and it will have some built in tools. One example is to use the built in java tools.
class NoLookingBack{
CountDownLatch latchB = new CountDownLatch(1);
public void methodA(){
//do work.
latchB.countDown();
}
public void methodB(){
try{
latchB.await();
} catch(InterruptException e){
//do something or declare this method throws.
return;
}
}
}
I think this shows how more methods could be included by adding more latches when necessary.
Your example is flawed, and so is this solution. What if methodA fails, then methodB will block forever. The latch gives you the power to use a timeout value, then you can use a response that indicates a failure.
How do I execute a method only after another finish?
you can take below approaches for the same
1) you can call second method from first method itself in the last of first method.
2) You can create a Asynctask and execute first method and after the first method is executed then onPostExecute method call another method
Calling a function after another function's callbacks are returned
The only way to make something like this work properly is to make y
asynchronous. Basically, y
internally waits for x
to complete before executing its own code. This is similar to things like domready
or onload
which waits for other things to happen before executing their own logic.
There are two ways to accomplish this. The first, simplest and most naive way is setTimeout
polling. Make x
set a variable or attribute and check that before executing:
function y () {
if (x.ready) {
/* do what you need to do here */
}
else {
setTimeout(y,100);
}
}
The second method is to create virtual events or promises. Not all promise libraries support using a promise that has already expired (my own homemade one does) so you may need to write your own control flow to handle that case. For this you need to rewrite x
to support an event or promise-like api:
var x = (function () {
var async_calls = 2;
var callback;
f = function () {
console.log('x is called');
async_call_one(function(){
async_calls --;
if (async_calls == 0 && callback) callback();
callback_one();
});
async_call_two(function(){
async_calls --;
if (async_calls == 0 && callback) callback();
callback_two();
});
}
f.loaded = function (loaded_callback) {
callback = loaded_callback;
if (async_calls == 0) callback();
}
return f;
})();
Now in y
you can use the x.loaded
function to execute your code when x is loaded:
function y () {
x.loaded(function(){
/* do what you need to do here */
});
}
Of course, this has the problem of making y
asynchronous. Therefore if your users expect to write something like:
y();
a();
b();
then a
and b
may or may not execute before y
. To solve this you need to make y
accept a callback so that you users can control their program flow:
function y (callback) {
if (x.ready) {
/* do what you need to do here */
callback();
}
else {
setTimeout(function(){y(callback)},100);
}
}
or:
function y (callback) {
x.loaded(function(){
/* do what you need to do here */
callback();
});
}
So they'd have to use y
like this:
y(function(){
a();
b();
});
Alternatively you can make y
return a promise if you prefer that style.
Forcing a function to wait until another function is complete
You want to use promises if you have asynchronous code. Promise.all() will wait for them all to be complete before running.
function task1() { return new Promise(function(resolve, reject) { console.log("task 1") setTimeout(function() { resolve('foo'); }, Math.random() * 2000); })}
function task2() { return new Promise(function(resolve, reject) { console.log("task 2") setTimeout(function() { resolve('bar'); }, Math.random() * 2000); })}
function task3() { console.log("task 3")}
Promise.all([task1(), task2()]).then(function(values) { console.log(values); task3()});
call second function after first is complete
you can use await and async for this
function f1() {
return "value"
}
async function f2() {
let result = await f1();
console.log(result);
}
f2();
Related Topics
Eclipse No Tests Found Using Junit 5 Caused by Noclassdeffounderror for Launcherfactory
Regular Expression to Validate Username
How to Check Heap Usage of a Running Jvm from the Command Line
Map Json String Column of a JPA Entity to Java Object Automatically
Keytool Error Bash: Keytool: Command Not Found
Post and Get for the Same Url - Controller - Spring
How to Call an Excel Vba Macro from Java Code
Java Ssl: How to Disable Hostname Verification
Checking If a String Is Contained in an Enum Set in O(1)
How to Exclude an Android App from Battery Optimization Using Code
Kafka: How to Delete Records from a Topic Using Java API
Notifydatasetchanged() Makes the List Refresh and Scroll Jumps Back to the Top
How to Stop the Items Duplication in Recyclerview Android
Object Cannot Be Converted to Integer Error
How to Send Text to Textarea in Div Element Using Selenium