如何添加 2 个开放功能但延迟一个?

我需要制作一个应用程序,它使用功能工具来戳狗,然后延迟它来戳一个老人。你能帮助我使用功能工具来冲压 2 个物体吗(不是同时)?谢谢你。


我试过用...


function open2() {

  // code here

}

而且我也尝试使用...


function open() {

  // code here

}

对于他们俩


function open(){

  stamp ('dog14',600,850,200)

  sound ('dog')


  sound('old man')

  stamp('old man',300,700)

}

当我使用该代码时,狗和老人同时被盖章,但我需要在狗之后 3 秒盖章老人。


HUH函数
浏览 153回答 2
2回答

LEATH

您可以定义一个函数并包含超时。包含Promises是管理异步操作的更简单的替代方法。下面是四个函数:邮票(图)声音(图)邮票和声音(图)如果figure为空或未定义,则承诺会被拒绝。该catch方法捕获并记录返回的内容。在这种情况下,'Nothing to stamp and sound'返回。否则,stamp和sound被调用,并承诺做出决议返回一个异步操作。打开()function stamp(figure){  console.log(figure + ' stamped');}function sound(figure){  console.log(figure + ' sounded');}function stampAndSound(figure) {  return new Promise(function(resolve, reject) {    // if empty argument is given, reject promise    if(figure === undefined || figure == ''){       reject('Nothing to stamp and sound');    }else{      // otherwise stamp and sound       stamp(figure);      sound(figure);      resolve();    }  })}// define variables ...let oldMan = 'old man';//let dog = '';  // uncomment this line and comment the one below to test how the promise rejectslet dog = 'pitbull';function open(){  // stampAndSound oldMan first then dog  stampAndSound(oldMan).then(function() {    // wait three seconds then stamp and sound dog    setTimeout(function(){      stampAndSound(dog).catch(function(error){ // if promise gets rejected..         console.log('Error: ' + error);      });    }, 3000)   }).catch(function(error){ // if promise gets rejected..     console.log('Error: ' + error);  })}open();ES6 语法const stamp = (figure) => {  console.log(`${figure} stamped`); }const sound = (figure) => { console.log(`${figure} sounded`); }const stampAndSound = (figure) => {  return new Promise((resolve, reject) => {    if(figure === undefined || figure == ''){       reject('Nothing to stamp and sound');    }else{      stamp(figure);      sound(figure);      resolve();    }  })}// define variables ...let oldMan = 'old man';let dog = 'pitbull';const open = () => {  stampAndSound(oldMan).then(() => {    setTimeout(() => {      stampAndSound(dog).catch((error) => {        console.log('Error: ' + error);      });    }, 3000);   }).catch((error) => {     console.log('Error: ' + error);  })}open();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript