JavaScript/sleep:修订间差异
来自康健生活
小 文字替换 -“{{leftrightflex|”替换为“{{Double-columns|” 标签:ReplaceText 移动版编辑 移动版网页编辑 |
|||
| (未显示同一用户的3个中间版本) | |||
| 第2行: | 第2行: | ||
== 模拟 == | == 模拟 == | ||
=== es5 === | === es5 === | ||
{{ | {{Double-columns|<syntaxhighlight lang="javascript"> | ||
var sleep = function(time) { | var sleep = function(time) { | ||
var startTime = new Date().getTime() + parseInt(time, 10); | var startTime = new Date().getTime() + parseInt(time, 10); | ||
| 第24行: | 第24行: | ||
})</syntaxhighlight> | })</syntaxhighlight> | ||
{{ | {{Double-columns|<syntaxhighlight lang="javascript"> | ||
function* sleep(ms){ | function* sleep(ms){ | ||
yield new Promise(function(resolve,reject){ | yield new Promise(function(resolve,reject){ | ||
| 第40行: | 第40行: | ||
同步执行 | 同步执行 | ||
{{ | {{Double-columns|<syntaxhighlight lang="javascript"> | ||
function sleep (time) { | function sleep (time) { | ||
return new Promise((resolve) => setTimeout(resolve, time)); | return new Promise((resolve) => setTimeout(resolve, time)); | ||
| 第52行: | 第52行: | ||
Promise {<pending>} | Promise {<pending>} | ||
Do other things, Wed Jun 24 2020 23:42:31 GMT+0800 (中国标准时间) | Do other things, Wed Jun 24 2020 23:42:31 GMT+0800 (中国标准时间) | ||
</pre>}}}} | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
function sleep (time) { | |||
return new Promise((resolve) => setTimeout(resolve, time)); | |||
} | |||
async function usetest() { | |||
var temple=await sleep(1000); | |||
console.log('mark~'); | |||
return temple | |||
} | |||
usetest();</syntaxhighlight>|{{consoleout|<pre> | |||
Promise {<pending>} | |||
mark~ | |||
</pre>}}}} | </pre>}}}} | ||
{{unknown}} | {{unknown}} | ||
== co == | |||
<syntaxhighlight lang="javascript"> | |||
function sleep(ms) { | |||
return function (cb) { | |||
setTimeout(cb, ms); | |||
} | |||
} | |||
co(function *() { | |||
var now = Date.now(); | |||
yield sleep(2000); | |||
expect(Date.now() - now).to.not.be.below(2000); | |||
}); | |||
</syntaxhighlight> | |||