神刀安全网

JavaScript sleep Function

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.

Writing a sleep function is simple and made even more usable withJavaScript 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! })

Withoutpromises 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.

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » JavaScript sleep Function

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址