Advertisement
Guest User

Untitled

a guest
Jun 25th, 2019
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. /**
  2. * Cuts down potentially long or infinite loops to prevent blocking the event loop.
  3. *
  4. * Example:
  5. * snip(10, 500, function*() {
  6. * for (let i = 0; i < 1e100; i++, yield) {
  7. * console.log(i);
  8. * }
  9. * console.log('Done!');
  10. * });
  11. *
  12. * let check = false;
  13. * snip(1, 1000, function*() {
  14. * while (!check) {
  15. * console.log('check = false');
  16. * yield;
  17. * }
  18. * console.log('Done!');
  19. * });
  20. * setTimeout(() => check = true, 10000);
  21. *
  22. * @param {number} interval The number of times that `yield` will be called until it times out.
  23. * @param {number} cooldown The amount of time in milliseconds between each interval.
  24. * @param {function*(): any} gen The generator function. Each `yield` gives the current count within the interval (from 0 to interval).
  25. * @return {Promise<any>} Gives the return value of gen.
  26. */
  27. function snip(interval, cooldown, gen) {
  28. return new Promise(function(resolve, reject) {
  29. let g = gen(), v, i;
  30. setTimeout(function loop() {
  31. try {
  32. for (i = 0; i < interval; i++) {
  33. v = g.next(i);
  34. if (v.done) {
  35. this.ended = true;
  36. resolve(v.value);
  37. return;
  38. }
  39. }
  40. setTimeout(loop, cooldown);
  41. } catch (e) {
  42. reject(e);
  43. }
  44. }, 0);
  45. });
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement