4

I know you will all be going like "use timers!" but let me explain. I'm making something like macro and I need functions to be executed with a specific delay. I know that it can be done with timers, but how would a code look with 50 timers and 50 callbacks for them? With sleep it could be all nice in one function. Since web workers run on separate thread, there is no problem of freezing.

I only know 2 methods of making sleep without eating cpu:

  1. Make a synchronous xhr request to a special backend that sleeps for x amount of seconds given by GET. While this works it's really inconvenient and depends on ping to the server.
  2. Use generator functions (yield) and send a message to main thread which starts a timer. When timer executes, message is sent back to the worker to continue execution. This is a very good solution but it's only available in firefox as I know. Chrome has no support of generator functions.

Are there any other ways of achieving sleep function?

Intel
  • 61
  • 6
  • I am not sure that this belongs on StackOverflow, I am going to flag for migration to [Programmers.Stackexchange.com](http://Programmers.StackExchange.com), and see what the Moderators think. – Malachi Oct 03 '13 at 20:59
  • Chrome does support generators. Enable Harmony support via `chrome://flags/`, then you can create a generator using `var generator = function*() { /*do something*/ yield 1; /* do something else*/ yield 2; /* finish your stuff */}; var g = generator();g.next(); /*when you're ready...*/ g.next(); // etc` – Rob W Oct 08 '13 at 12:06

1 Answers1

0

There is solution - spin lock.

var d1 = Date.now();
while(Date.now() < d1+50) {
     // do nothing
}

Of course, it isn't optimal. Your question states that you have considered generators. Generators are great for solving problems like this. But can we use generators? Native syntax for generators isn't widely adopted in browsers.

But we can use solutions build for supporting generators in ES5. You can use following transpilers:

Ginden
  • 5,149
  • 34
  • 68