JavaScript/sleep:修订间差异
来自康健生活
小 文字替换 -“{{leftrightflex|”替换为“{{Double-columns|” 标签:ReplaceText 移动版编辑 移动版网页编辑 |
|||
| (未显示同一用户的6个中间版本) | |||
| 第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); | ||
| 第12行: | 第12行: | ||
43322 mark~ | 43322 mark~ | ||
</pre>}}}} | </pre>}}}} | ||
进程阻塞、性能和负载问题 | |||
=== es6 === | === es6 === | ||
<syntaxhighlight lang="javascript"> | <syntaxhighlight lang="javascript"> | ||
| 第20行: | 第23行: | ||
// ... | // ... | ||
})</syntaxhighlight> | })</syntaxhighlight> | ||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
function* sleep(ms){ | |||
yield new Promise(function(resolve,reject){ | |||
console.log('mark~'); | |||
setTimeout(resolve,ms); | |||
}) | |||
} | |||
sleep(500).next().value.then(()=>{ | |||
console.log('mark,end~'); | |||
})</syntaxhighlight>|{{consoleout|<pre> | |||
mark~ | |||
Promise {<pending>} | |||
mark,end~ | |||
</pre>}}}} | |||
同步执行 | 同步执行 | ||
{{ | {{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)); | ||
| 第34行: | 第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> | |||