猿问

暂停jQuery或JavaScript中的函数

我想在添加每个数字时停止此功能几秒钟,但此功能无法按预期工作。


function yazmaeffetkti() {

  var cumleler = ["salam necesen", "yaxsiyam sen "]

  currentcumle = ""

  for (var i = 0; i < cumleler.length; i++) {

    cumle = cumleler[i]

    for (var z = 0; z < cumle.length; z++) {

      currentcumle += cumle[z]


      function stateChange(currentcumle) {

        setTimeout(function() {

          console.log(currentcumle);

        }, 3000);

      }

      stateChange(currentcumle)

    }

    currentcumle = ""

  }

}


yazmaeffetkti()


饮歌长啸
浏览 93回答 3
3回答

胡子哥哥

实现这一目标的最简洁方法是使用asyncand await:async function yazmaeffetkti() {&nbsp; &nbsp; // ...&nbsp; &nbsp; await new Promise(resolve => setTimeout(resolve, 3000));&nbsp; &nbsp; console.log(currentcumle);&nbsp; &nbsp; // ...}

守候你守候我

除了Robo Robok 的回答之外,这里是一个使用相同概念但使用then代替的示例async/await。我个人更喜欢它,但这取决于你。function yazmaeffetkti() {&nbsp; var cumleler = ["salam necesen", "yaxsiyam sen "]&nbsp; currentcumle = ""&nbsp; for (var i = 0; i < cumleler.length; i++) {&nbsp; &nbsp; cumle = cumleler[i]&nbsp; &nbsp; for (var z = 0; z < cumle.length; z++) {&nbsp; &nbsp; &nbsp; currentcumle += cumle[z]&nbsp; &nbsp; &nbsp; new Promise(resolve => setTimeout(resolve, 3000)).then(() => {&nbsp; &nbsp; &nbsp; &nbsp; console.log(currentcumle);&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }&nbsp; &nbsp; currentcumle = ""&nbsp; }}yazmaeffetkti()

largeQ

这是我的版本:async function yazmaeffetkti() {&nbsp; var cumleler = ["salam necesen", "yaxsiyam sen "]&nbsp; currentcumle = ""&nbsp; for (var i = 0; i < cumleler.length; i++) {&nbsp; &nbsp; cumle = cumleler[i]&nbsp; &nbsp; for (var z = 0; z < cumle.length; z++) {&nbsp; &nbsp; &nbsp; currentcumle += cumle[z]&nbsp; &nbsp; &nbsp; await stateChange(currentcumle)&nbsp; &nbsp; }&nbsp; &nbsp; currentcumle = ""&nbsp; }}var stateChange = (currentcumle) => new Promise((resolve)=>{&nbsp; &nbsp; setTimeout(function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(currentcumle);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; resolve(true);&nbsp; &nbsp; }, 1000);&nbsp; });yazmaeffetkti()
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答