【问题标题】:How can I call a function when another have been executed执行另一个函数时如何调用函数
【发布时间】:2022-01-21 12:34:33
【问题描述】:

我是 JavaScript 的完全初学者。我只想在函数 firstOne() 完成执行后调用名为 seconONE() 的函数。这么说,我的意思是当 p1 的值为 4 时,函数二将调用(在这种情况下);我可以通过调用 setTimeout() 函数来实现它。但是如果我不知道执行 { 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);
    }
}

【问题讨论】:

  • 回调是你的朋友 :) w3schools.com/js/js_callback.asp 但是,请问你为什么使用 setTimeout?
  • “到底是什么事件循环?| Philip Roberts | JSConf EU”youtube.com/watch?v=8aGhZQkoFbQ
  • 我只想创建一个元素的值每秒或更多和更少时间增加的部分!。并且只是为了确保用户可以看到我使用超时功能的增量!

标签: javascript function delayed-execution asynchronous-javascript


【解决方案1】:

一个可能的解决方案是使用 promises。更多关于 Promise 的信息here

工作示例

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"))
  })

【讨论】:

  • 您应该更新您的 sn-p 代码以使其正常工作。
  • 如你所愿@Andy
【解决方案2】:

你的问题一点也不幼稚。您需要了解的是回调和承诺处理程序。这只是告诉 JavaScript 等待任务完成才能执行下一个任务。

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

【讨论】:

    【解决方案3】:

    将 if 条件放入您的 firstOne 函数中。

    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);
        }
    }
    

    【讨论】:

      【解决方案4】:

      只是建立在具有suggested using a Promise 的其他答案的基础上,这里有一个更通用的解决方案,它也使用async/await

      (总而言之:调用一个带有计数和一个元素的函数。该函数将返回一个承诺,即“在某个时候”工作将完成。内部函数循环更新元素内容,直到达到该计数,在这一点上,promise 解决了,接下来的事情就可以开始了)。

      // 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>

      其他文档

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多