Javascript-форум (https://javascript.ru/forum/)
-   Элементы интерфейса (https://javascript.ru/forum/dom-window/)
-   -   Запуск большого количества таймеров. (https://javascript.ru/forum/dom-window/77657-zapusk-bolshogo-kolichestva-tajjmerov.html)

dima85 03.06.2019 10:59

Запуск большого количества таймеров.
 
По очереди через разный промежуток времени срабатывает таймер и стучится в нужные мне функции.
Я это реализовал так. Всего таких таймеров около 10.
setTimeout(function () {
     console.log('test1');
}, 10500);
setTimeout(function () {
     console.log('test3');
}, 14500);
setTimeout(function () {
     console.log('test');
}, 15000);


Подскажите как этот код сделать более красивым.

рони 03.06.2019 11:49

dima85,
class Timer {
    constructor(data) {
    this.data = data.map(obj => ({...obj,beginTime : performance.now()}));
    requestAnimationFrame(this.loop.bind(this));
    }
    loop(time){
      this.data = this.data.filter(({beginTime,duration,fn}) => {
         const end = time - beginTime >= duration;
         if(end) {
           fn()
         }
         else return true
      })
      this.data.length && requestAnimationFrame(this.loop.bind(this))
    }

    }
    new Timer([
    {duration : 10500, fn : ()=> console.log('test1')},
    {duration : 14500, fn : ()=> console.log('test3')},
    {duration : 15000, fn : ()=> console.log('test')},
    ])

dima85 05.06.2019 10:49

Спасибо!
Подскажите как в new Timer([]); добавить значения с переменной.
Есть файл test.txt в нем:
{duration : 10500, fn : ()=> console.log('test1')},
{duration : 14500, fn : ()=> console.log('test3')},
{duration : 15000, fn : ()=> console.log('test')},



Я его подгружаю на страницу примерно так, в переменную responses у меня попадает все с test.txt
И далее я пытаюсь это вставить в Timer, но видимо responses надо как-то сказать что в нем массив а не простой текс. Подскажите как это сделать.
ajax.get('test.txt',{},function(responses){
     new Timer([responses]);
    },true);

рони 05.06.2019 11:17

Цитата:

Сообщение от dima85
test.txt

может сделать json и тогда new Timer(responses);

dima85 05.06.2019 12:16

Хорошо, тогда нам надо немного поменять файл, например на такой:
[{"duration" : 10500, "console":"test1"},
{"duration" : 14500, "console":"test3"},
{"duration" : 15000, "console":"test"}]


Далее:
ajax.get('test.txt',{},function(responses){
     new Timer(JSON.parse(responses));
    },true);


А как здесь?:
class Timer {
    constructor(data) {
    this.data = data.map(obj => ({...obj,beginTime : performance.now()}));
    requestAnimationFrame(this.loop.bind(this));
    }
    loop(time){
      this.data = this.data.filter({beginTime,duration,fn} => {
         const end = time - beginTime >= duration;
         if(end) {
           fn() //?????
         }
         else return true
      })
      this.data.length && requestAnimationFrame(this.loop.bind(this))
    }

    }

рони 05.06.2019 12:22

dima85,
class Timer {
    constructor(data) {
    this.data = data.map(obj => ({...obj,beginTime : performance.now()}));
    requestAnimationFrame(this.loop.bind(this));
    }
    loop(time){
      this.data = this.data.filter(({beginTime,duration,fn}) => {
         const end = time - beginTime >= duration;
         if(end) {
           fn()
         }
         else return true
      })
      this.data.length && requestAnimationFrame(this.loop.bind(this))
    }

    }

    let responses = `{duration : 10500, fn : ()=> console.log('test1')},
    {duration : 14500, fn : ()=> console.log('test3')},
    {duration : 15000, fn : ()=> console.log('test')}`
    responses = eval(`[${responses}]`)
    new Timer(responses)

рони 05.06.2019 12:28

dima85,
class Timer {
    constructor(data) {
    this.data = data.map(obj => ({...obj,beginTime : performance.now()}));
    requestAnimationFrame(this.loop.bind(this));
    }
    loop(time){
      this.data = this.data.filter(({beginTime,duration,"console" : txt}) => {
         const end = time - beginTime >= duration;
         if(end) {
           console.log(txt)
         }
         else return true
      })
      this.data.length && requestAnimationFrame(this.loop.bind(this))
    }

    }

    let responses =
[{"duration" : 10500, "console":"test1"},
{"duration" : 14500, "console":"test3"},
{"duration" : 15000, "console":"test"}]
    new Timer(responses)

рони 05.06.2019 12:33

dima85,
обратите внимание, строка 7 исправлена везде!!!


Часовой пояс GMT +3, время: 07:13.