简体   繁体   中英

How can I call a function when another have been executed

I'm a complete beginner at JavaScript. I just want to call the function called seconONe() just after the function firstOne() completes its execution. by saying this, I mean the function two will call when the value of that p1 is 4 ( in this case ); I can achieve it by calling a setTimeout() function. but what if I don't know how many does it take to execute { the first one() }?

 // getting DOM element
const p1 = document.getElementById(`one`);
const p2 = document.getElementById(`two`);
const p3 = document.getElementById(`three`);

// first function
function firstOne() {
    for (let i = 0; i < 5; i++) {
        setTimeout(() => {
            p1.innerHTML = i;
        }, i * 1000);
    }
}

// second function
function seconOne() {
    for (let i = 0; i < 5; i++) {
        setTimeout(() => {
            p2.innerHTML = i;
        }, i * 1000);
    }
}

A possible solution is to work with promises . More info about promises here .

Working example

 var p1 = 1; var p2 = 2; var p3 = 3; const firstPromise = new Promise((resolve, reject) => { for (let i = 0; i < 5; i++) { setTimeout(() => { p1 = i; }, i * 1000); } resolve() }); const secondPromise = new Promise((resolve, reject) => { for (let i = 0; i < 5; i++) { setTimeout(() => { p2 = i; }, i * 1000); } resolve() }); //run first promise console.log("First promise called") firstPromise.then((response) => { console.log("First promise done") //run second promise after first promise succeed console.log("Second promise called") secondPromise.then((response) => console.log("Second promise done")) })

your question is not childish at all. What you will need to understand are callbacks and promise handlers. This just tells JavaScript to wait till a task has been completed in order to execute the next task.

firstOne().then(() => secondOne())

put if condition in your firstOne function.

const p1 = document.getElementById(`one`);
const p2 = document.getElementById(`two`);
const p3 = document.getElementById(`three`);

// first function
function firstOne() {
    for (let i = 0; i < 5; i++) {
        setTimeout(() => {
            if(i == 4){
               seconOne();
            }else{
                p1.innerHTML = i;
            }
        }, i * 1000);
    }
}

// second function
function seconOne() {
    for (let i = 0; i < 5; i++) {
        setTimeout(() => {
            p2.innerHTML = i;
        }, i * 1000);
    }
}

Just to build on the other answers that have suggested using a Promise , here's a more generalised solution that also uses async/await .

(In summary: call a function with a count, and an element. That function will return a promise that "at some point" work will be completed. An inner function loops updating the element content until that count has been reached, at which point the promise resolves, and the next thing can start).

 // Cache the elements const p1 = document.querySelector('#one'); const p2 = document.querySelector('#two'); const p3 = document.querySelector('#three'); // `timer` accepts a count, and the element // to apply the count to function timer(count, el) { // Return a promise that basically says: // once I'm done doing this work, resolve, // and then the event queue can // get on with the next thing return new Promise(resolve => { // So we create a loop that logs the numbers // in our element up to the count we specified. // and when that number is reached, resolve the promise function loop(n = 0) { // If our current `n` value is <= count if (n <= count) { // Set the content of the element el.textContent = n; // Call `loop` again after a second // with an incremented `n` value setTimeout(loop, 1000, ++n); // Otherwise resolve the promise } else { resolve(); } } loop(); }); } // And now we just await each resolved promise async function main() { await timer(4, p1); await timer(7, p2); await timer(20, p3); console.log('Done;'); } main();
 <div id="one"></div> <div id="two"></div> <div id="three"></div>

Additional documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM