Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //copypaste from http://pastebin.com/YCFQr4xQ
- function Sync() {
- var lock = 0, queue = [];
- this.append = function(cb, args) {
- queue.push( [cb, args] );
- }
- this.next = function() {
- lock = 0;
- }
- this.wait = function() {
- if (!lock && queue.length) {
- lock = 1;
- var item = queue.shift();
- item[0].apply( null, item[1] );
- }
- }
- }
- console.log(Math.floor(new Date().getTime() / 1000) + ' асинх. функция1 ждём 2 сек.');
- setTimeout(function() {
- console.log(Math.floor(new Date().getTime() / 1000) + ' асинх. функция1 выполнена.');
- }, 2000);
- console.log(Math.floor(new Date().getTime() / 1000) + ' асинх. функция2 ждём 3 сек.');
- setTimeout(function() {
- console.log(Math.floor(new Date().getTime() / 1000) + ' асинх. функция2 выполнена.');
- }, 3000);
- var sync = new Sync();
- sync.append(function() {
- console.log(Math.floor(new Date().getTime() / 1000) + ' синх. функция1 ждём 2 сек.');
- setTimeout(function() {
- console.log(Math.floor(new Date().getTime() / 1000) + ' синх. функция1 выполнена.');
- // снимаем блокировку и вызываем следующий обработчик
- sync.next();
- }, 2000);
- });
- sync.append(function() {
- console.log(Math.floor(new Date().getTime() / 1000) + ' синх. функция2 ждём 3 сек.');
- setTimeout(function() {
- console.log(Math.floor(new Date().getTime() / 1000) + ' синх. функция2 выполнена.');
- sync.next();
- }, 3000);
- });
- setTimeout(function() {
- // будет выполена после второй синхронной
- sync.append(function() {
- console.log(Math.floor(new Date().getTime() / 1000) + ' синх. функция3 выполена.');
- sync.next();
- });
- }, 1000);
- setInterval(function() {
- console.log('Ждем..')
- sync.wait();
- }, 40);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement