1.setTimeout方法进行休眠操作
function firstStep() {
//do something
setTimeout("secondStep()", 1000);
}
function secondStep() {
//do something
setTimeout("thirdStep()", 1000);
}
function thirdStep() {
//do something
}
2.js封装sleep的方法
async function test() {
console.log('Hello')
await sleep(1000)
console.log('world!')
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
测试方法1:
1. 安装iojs(https://iojs.org/)
2. 安装babel(执行 npm install babel –global)
3. 将上述代码保存为 test.js
4. 执行 babel-node –stage=1 test.js
测试方法2:
1. 打开Chrome安装Scratch JS扩展(Scratch JS - Chrome Web Store)【可能需要翻墙】
2. 打开Chrome的开发者工具,选择「Scratch JS」tab
3. 将上述代码粘贴进去
4. 点击 Run it 按钮
3. 每隔2000毫秒执行一次test()函数,执行无数次。
setInterval("方法","2000");