JavaScript/sleep:修订间差异
来自康健生活
创建页面,内容为“== 引用 == == 模拟 == <syntaxhighlight lang="javascript"> function sleep (time) { return new Promise((resolve) => setTimeout(resolve, time)); } sleep(500).the…” |
小 文字替换 -“{{leftrightflex|”替换为“{{Double-columns|” 标签:ReplaceText 移动版编辑 移动版网页编辑 |
||
| (未显示同一用户的9个中间版本) | |||
| 第1行: | 第1行: | ||
== 引用 == | == 引用 == | ||
== 模拟 == | == 模拟 == | ||
=== es5 === | |||
{{Double-columns|<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(() => { | ||
// ... | // ... | ||
})</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) { | |||
return new Promise((resolve) => setTimeout(resolve, time)); | |||
} | |||
(async function() { | |||
console.log('Do some thing, ' + new Date()); | |||
await sleep(3000); | |||
console.log('Do other things, ' + new Date()); | |||
})();</syntaxhighlight>|{{consoleout|<pre> | |||
Do some thing, Wed Jun 24 2020 23:42:28 GMT+0800 (中国标准时间) | |||
Promise {<pending>} | |||
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>}}}} | |||
{{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> | |||