0

Есть таймер написанный на ООП. По истечению заданного таймера. страница должна обновляться.

В коде таймер уходит в отрицательные значения.

'use strict';

window.onload = function(e) {

  let t1 = new Timer(60);

  document.querySelector('.res').innerHTML = t1.getTime();
  if (t1.getTime == 0) {
    location.reload();
  }

};

class Timer {
  constructor(t = 60) {
    this.time = t;
  }

  tick() {
    this.time--;
    console.log(this.time);
  };

  run() {
    setInterval(() => {
      this.tick();
    }, 1000);
  };

  getTime() {
    return this.time;
  }

}
<div class="res"></div>

2
  • что такое ©обновлялась страница
    – qwabra
    6 янв 2020 в 15:22
  • @qwabra это когда вместо нажатия на F5, страница сама это делает
    – Imp3l
    6 янв 2020 в 15:24

3 ответа 3

1

"use strict";
class Timer extends EventTarget {
    constructor(_time = 60) {
        super();
        this._time = _time;
        this._interval = null;
    }
    tick() {
        this._time--;
        console.log(this._time);
        if (this._time === 0) {
            if (this._interval)
                clearInterval(this._interval);
            const e = new Event('time');
            this.dispatchEvent(e);
        }
    }
    run() {
        this._interval = setInterval(() => {
            this.tick();
        }, 1000);
    }
    ;
    getTime() {
        return this._time;
    }
}
const t = new Timer(8);
t.addEventListener('time', () => {
    console.log('Show Must Go On');
});
t.run();

песочница, TypeScript

1
  let t1 = new Timer(60);
  t1.addEventListener(t => {
    document.querySelector('.res').innerHTML = t.getTime();
    if (t.getTime() <= 0)
      location.reload();
  });


class Timer {
  constructor(t = 60) {
    this.time = t;
    this.listeners = [];
  }

  tick() {
    this.time--;
    console.log(this.time);
    this.listeners.forEach(i => i(this));
  }
  ...
  addEventListener(listener) {
    this.listeners.push(listener);
  }
}
1
  • по ООП сущность должна делать только что-то одно. В вашем случае она еще и обновляет страницу.
    – Imp3l
    6 янв 2020 в 15:28
1

'use strict';

class Timer {
  #time;
  #interval;

  constructor({ time=60, onTick, onDone } = {}) {
    Object.assign(this, { onTick, onDone });
    this.#time = ++time;
  }

  get time() {
    return this.#time;
  }

  tick() {
    if (--this.#time <= 0) {
      if (typeof this.onDone === 'function')
        this.onDone.call(this);
      return clearInterval(this.#interval);
    }
    if (typeof this.onTick === 'function')
      this.onTick.call(this, this.#time);
  }

  run() {
    this.#interval = setInterval(() => this.tick(), 1000);
    this.tick();
  }
}

document.addEventListener('DOMContentLoaded', () => {
  const output = document.querySelector('.res');
  const timer = new Timer({
    time: 15,
    onTick(time) { output.textContent = time; },
    onDone() { window.location.reload(); },
  });
  timer.run();
});
<div class="res"></div>

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.