stuppid_bot

Javascript синхронизация асинхронных функций

Mar 27th, 2013
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function Sync() {
  2.     var lock = 0, queue = [];
  3.    
  4.     this.append = function(cb, args) {
  5.         queue.push( [cb, args] );
  6.     }
  7.    
  8.     this.next = function() {      
  9.         lock = 0;
  10.     }
  11.    
  12.     this.wait = function() {  
  13.         if (!lock && queue.length) {
  14.             lock = 1;
  15.             var item = queue.shift();
  16.             item[0].apply( null, item[1] );
  17.         }
  18.     }
  19. }
  20.  
  21. console.log(Math.floor(new Date().getTime() / 1000) + ' асинх. функция1 ждём 2 сек.');
  22.  
  23. setTimeout(function() {
  24.     console.log(Math.floor(new Date().getTime() / 1000) + ' асинх. функция1 выполнена.');
  25. }, 2000);
  26.  
  27. console.log(Math.floor(new Date().getTime() / 1000) + ' асинх. функция2 ждём 3 сек.');
  28.  
  29. setTimeout(function() {
  30.     console.log(Math.floor(new Date().getTime() / 1000) + ' асинх. функция2 выполнена.');
  31. }, 3000);
  32.  
  33. var sync = new Sync();
  34.  
  35. sync.append(function() {
  36.     console.log(Math.floor(new Date().getTime() / 1000) + ' синх. функция1 ждём 2 сек.');
  37.    
  38.     setTimeout(function() {
  39.         console.log(Math.floor(new Date().getTime() / 1000) + ' синх. функция1 выполнена.');
  40.         // снимаем блокировку и вызываем следующий обработчик
  41.         sync.next();
  42.     }, 2000);
  43. });
  44.  
  45. sync.append(function() {
  46.     console.log(Math.floor(new Date().getTime() / 1000) + ' синх. функция2 ждём 3 сек.');
  47.    
  48.     setTimeout(function() {
  49.         console.log(Math.floor(new Date().getTime() / 1000) + ' синх. функция2 выполнена.');
  50.         sync.next();
  51.     }, 3000);
  52. });
  53.  
  54. setTimeout(function() {
  55.     // будет выполена после второй синхронной
  56.     sync.append(function() {
  57.         console.log(Math.floor(new Date().getTime() / 1000) + ' синх. функция3 выполена.');
  58.         sync.next();
  59.     });
  60. }, 1000);
  61.  
  62. setInterval(function() {
  63.     console.log('Ждем..')
  64.     sync.wait();
  65. }, 40);
Advertisement
Add Comment
Please, Sign In to add comment