Reputation:
I have two onclick
functions on page:
function fn_name_1() {
//do buch of stuff
}
function fn_name_2() {
//do buch of stuff
}
When user clicks on fn_name_1()
it starts executing which is take a while (about 4 seconds to complete).
If user clicks on fn_name_2()
while fn_name_1()
is in process it messes fn_name_1()
.
I had tried to setTimeOut
for several second for fn_name_2()
but it an awful user experience because when they hit the button they expect immediate result on their actions.
Basically I want to:
Scenario 1
User hit fn_name_2()
button, its check if fn_name_1()
is running and if it is not - proceed with executing fn_name_2()
as normal.
Scenario 2
User hit fn_name_2()
button, its check if fn_name_1()
is running and if it dit, wait for completion and start executing automatically right after fn_name_1()
is completed.
How it can be solved?
Upvotes: 0
Views: 63
Reputation: 138407
Make fn_name_1 asynchronous, and let it return a promise, then you can store that promise, and only execute the second task when the promise resolved:
function fn_name_1() {
//do buch of stuff
return new Promise(resolve => {
setTimeout(resolve, 1000);
});
}
let isDone = fn_name_1();
function fn_name_2() {
isDone.then(() => {
//do buch of stuff
});
}
Upvotes: 1
Reputation: 1
something like this?
var wait=false;
function fn_name_1() {
wait=true;
//do bunch of stuff
wait=false;
}
function fn_name_2() {
while(wait){/*do nothing*/}
//do bunch of stuff
}
Upvotes: -1
Reputation: 6466
The simplest way is to have a variable which is accessible to both functions:
let runningTestOne = false;
function testOne(callback) {
console.log('Starting testOne');
runningTestOne = true;
setTimeout(() => {
runningTestOne = false;
console.log('done with testOne');
if (callback) {
callback();
}
}, 5000);
};
function testTwo() {
if (runningTestOne) {
console.log('cannot run');
return;
} else {
console.log('can run test two');
}
};
function runWithCallback() {
testOne(testTwo);
}
<button onclick="testOne()">Test One</button>
<button onclick="testTwo()">Test Two</button>
<button onclick="runWithCallback()">With callback</button>
Upvotes: 1