完成setTimeout后运行next函数

bsb*_*bak 13 javascript jquery

如何使它工作?请帮助.

function first() {
    setTimeout((function() {
        $('#q').append('first <br>');
    }), 1000);
}
function second() {
    $('#q').append('second <br>');
}
function third() {
    $('#q').append('third <br>');
}
$.when(first()).done(second()).done(third()); 
Run Code Online (Sandbox Code Playgroud)

first()作为最后一个函数运行,我首先需要

在这里小提琴:JSFIDDLE

Zee*_*Zee 13

我不确定你为什么这样做,但如果你想同步执行它们,你可以将第二和第三个函数调用放在setTimeout:

function first() {
    setTimeout(function() {
        $('#q').append('first <br>');
        second();
        third();
    }, 1000);
}
function second() {
    $('#q').append('second <br>');
}
function third() {
    $('#q').append('third <br>');
}
first();
Run Code Online (Sandbox Code Playgroud)


Joh*_*ohn 12

当你可以使用javascript promises时,你不需要延迟jquery .

function timeout (ms) {
  return new Promise(res => setTimeout(res,ms));
}

function first () {
  // $('#q').append('first <br>'); 
  console.log("first");
}

function second() {
  // $('#q').append('second <br>');
  console.log("second");
}

function third() {
  // $('#q').append('third <br>');
  console.log("third");
}

async function fireEvents () {
  // 2
  console.log("2. before await")
  await timeout(1000);
  // 4
  console.log("4. after await")
  first();
  second();
  third();
}

// 1
console.log("1. started");
fireEvents().then(()=>{
  // 5
  console.log("5. done")
});
// 3
console.log("3. after fireEvents");
Run Code Online (Sandbox Code Playgroud)
function first() {
   return new Promise(function(resolve, reject) {
     setTimeout((function() {
        $('#q').append('first <br>');
        resolve("Stuff worked!");
    }), 1000);
});
}
function second() {
    $('#q').append('second <br>');
}
function third() {
    $('#q').append('third <br>');
}
first().then(second).then(third); 
Run Code Online (Sandbox Code Playgroud)

执行最后一行的另一种方法fireEvents 是制作它

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="q"></div>
Run Code Online (Sandbox Code Playgroud)

你可以做到这一点,因为你知道第二和第三个函数是同步函数,而不像第一个异步函数.

编辑:使用javascript承诺背后的原因或在guest271314的答案jquery延迟是因为如果你想首先重用但在你的代码的不同部分完成之后调用第一或第二之后的东西你可以写一些东西到效果

first().then(function () {
  second();
  third();
});
Run Code Online (Sandbox Code Playgroud)

而且你会在不改变函数的情况下编写它.Promise和deferreds使异步代码更具可重用性.

编辑:

您现在还可以在执行第一个和第三个之前尝试async/await等待超时承诺.

first().then(function () {
  fourth();
  fifth();
});
Run Code Online (Sandbox Code Playgroud)