Advertisement
KiberInfinity

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

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