javascript功能
The infamous sleep
, or delay
, function within any language is much debated. Some will say that there should always be a signal or callback to fire a given functionality, others will argue that sometimes an arbitrary moment of delay is useful. I say that to each their own and one rule can never dictate anything in this industry.
臭名昭著的sleep
或delay
功能在任何语言中都存在很多争议。 有些人会说应该总是有一个信号或回调来触发给定的功能,另一些人则认为有时任意的延迟时间是有用的。 我说,在这个行业中,对每个人来说,一条规则永远不能决定任何事情。
Writing a sleep
function is simple and made even more usable with JavaScript Promises:
编写sleep
函数非常简单,并且可以通过JavaScript Promises进一步使用:
// https://zeit.co/blog/async-and-await
function sleep (time) {
return new Promise((resolve) => setTimeout(resolve, time));
}
// Usage!
sleep(500).then(() => {
// Do something after the sleep!
})
Without promises you'd need to pass a callback; with our beautiful promises we simply resolve after the setTimeout
and use then
with the result to execute the next step. You'll also note that the demo above uses ES6 arrow functions.
没有承诺,您将需要传递回调; 有了我们美好的承诺,我们只需在setTimeout
之后解决, then
其与结果一起使用即可执行下一步。 您还将注意到,上面的演示使用了ES6箭头功能 。
javascript功能