Guest User

Untitled

a guest
Mar 13th, 2019
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. let works = [];
  2. function tick() {
  3.     for (const work of works) {
  4.         work();
  5.     }
  6. }
  7. // add a work to the eventloop
  8. function enqueueWork(work) {
  9.     works.push(work);
  10. }
  11. // remove a work form the eventloop
  12. function dequeueWork(w) {
  13.     works = works.filter(o => o!==work);
  14. }
  15.  
  16. function setTimeout(f, t) {
  17.     const createdAt = Date.now();
  18.     enqueueWork(function work() {
  19.         if (createdAt + t < Date.now()) {
  20.             dequeueWork(work);
  21.             f();
  22.         }
  23.     });
  24. }
  25.  
  26.  
  27. function generateMessage(cb) {
  28.   setTimeout(() => {
  29.     cb('hello world!');
  30.   }, 1000);
  31. }
  32.  
  33. function msg() {
  34.     generateMessage((msg) => {
  35.         console.log('Message: ', msg);
  36.     });
  37. }
  38.  
  39. msg();
  40.  
  41. while (true) {
  42.     tick();
  43. }
Add Comment
Please, Sign In to add comment