JavaScript/sleep:修订间差异
来自康健生活
| 第1行: | 第1行: | ||
== 引用 == | == 引用 == | ||
== 模拟 == | == 模拟 == | ||
=== es5 === | |||
{{leftrightflex|<syntaxhighlight lang="javascript"> | |||
var sleep = function(time) { | |||
var startTime = new Date().getTime() + parseInt(time, 10); | |||
while(new Date().getTime() < startTime) { | |||
console.log('mark~'); | |||
} | |||
}; | |||
sleep(1000); </syntaxhighlight>|{{consoleout|<pre> | |||
43322 mark~ | |||
</pre>}}}} | |||
=== es6 === | |||
<syntaxhighlight lang="javascript"> | <syntaxhighlight lang="javascript"> | ||
function sleep (time) { | function sleep (time) { | ||
return new Promise((resolve) => setTimeout(resolve, time)); | return new Promise((resolve) => setTimeout(resolve, time)); | ||
} | } | ||
sleep(500).then(() => { | sleep(500).then(() => { | ||
// ... | // ... | ||
| 第15行: | 第26行: | ||
return new Promise((resolve) => setTimeout(resolve, time)); | return new Promise((resolve) => setTimeout(resolve, time)); | ||
} | } | ||
(async function() { | (async function() { | ||
console.log('Do some thing, ' + new Date()); | console.log('Do some thing, ' + new Date()); | ||
| 第23行: | 第33行: | ||
Do some thing, Wed Jun 24 2020 23:42:28 GMT+0800 (中国标准时间) | Do some thing, Wed Jun 24 2020 23:42:28 GMT+0800 (中国标准时间) | ||
Promise {<pending>} | Promise {<pending>} | ||
Do other things, Wed Jun 24 2020 23:42:31 GMT+0800 (中国标准时间) | |||
</pre>}}}} | </pre>}}}} | ||
{{unknown}} | {{unknown}} | ||