0

Делаю таймер обратного отсчета, все работает, но не знаю как реализовать продолжение отсчета с того места при клике на кнопку старт (тобото запущен таймер я нажимаю на стоп (таймер остановился) и после того нажимаю на кнопку еще раз и он продолжает отсчет с момента остановки (сейчас запускает заново))

const getId = id => document.getElementById(id);

const minutes = getId('minutes');
const secondTimer = getId('secondTimer')
let timerS;
let minut = 0;

getId('plus').onclick = function () {
    if (minut <= 59) {
        minut = +minut + 1;

        if (minut < 10) minut = '0' + minut;
    }
    minutes.innerHTML = minut;
}

getId('minus').onclick = function () {

    if (minut >= 1) {
        minut = +minut - 1;

        if (minut < 10) minut = '0' + minut;
    }
    minutes.innerHTML = minut;
}

function startTimer() {
    if (!timerS) {
        countdown( "secondTimer", minutes.innerHTML, 0 );

    }
}


function resetTimer() {
   stopTimer();
   startTimer();
}

function stopTimer() {
    clearInterval(timerS);
    timerS = false;
}

function countdown(element, minutes, seconds) {
    // встановити час для конкретного відліку
    let time = minutes*60 + seconds;
        timerS = setInterval(function() {
        let el = document.getElementById(element);
        // якщо час 0, то закінчіть лічильник
        if(time == 0) {
            el.innerHTML = "End";    
            clearInterval(timerS);
            timerS = false;
            return;
        }
        let minutes = Math.floor( time / 60 );
        if (minutes < 10) minutes = "0" + minutes;
        let seconds = time % 60;
        if (seconds < 10) seconds = "0" + seconds; 
        let text = minutes + ':' + seconds;
        el.innerHTML = text;
        time--;
    }, 1000);
}
 <div class="block">
        <div class="box">
            <div id="minutes">00</div>
            <p>MINUTES</p>
            <div class="buttons2">
                <button id="plus">+</button>
                <button id="minus">-</button>
            </div>

        </div>
        <div class="box">
            <div id="secondTimer">00:00</div>

            <div class="buttons">
                <button onclick="startTimer()">START</button>
                <button onclick="stopTimer()">STOP</button>
                <button onclick="resetTimer()">RESET</button>
            </div>

        </div>


    </div>

1 ответ 1

1

Как при остановке таймера продолжить работу с места остановки?

  • Запустить ф-ю старт.

Как при остановке таймера начать с начала?

  • Избавиться от данных.
  • Запустить ф-ю старт.
    • В которой занести в this.data исходные(изначальные) данные.

пример на TypeScript

class Timer<T extends {}> {
    #id: number

    start() {
        if (!this.data) this.data = Object.assign(Object.create(null), this.initData)
        if (!this.#id) this.#id = this.gen()
    }
    stop() {
        clearInterval(this.#id)
        this.#id = undefined
        this.data = undefined
    }
    pause() {
        clearInterval(this.#id)
        this.#id = undefined
    }

    data: T
    gen(): number {
        return setInterval(() => {
            this.foo(this.data)
        }, this.step)
    }

    constructor(
        private initData: T,
        private foo: (data: T) => void,
        private step: number = 1e3
    ) { }
}


test: {
    const t = new Timer({ counter: 0 }, data => {
        data.counter++
        console.log(data.counter)
    })
    test()
    function test() {
        t.start()
        setTimeout(() => {
            t.pause()
            setTimeout(() => {
                t.start()
                setTimeout(() => {
                    t.stop()
                    test()
                }, 3e3)
            }, 3e3)
        }, 5e3)
    }
}

P.S.

1e3 = 1000 -> 1 секунда

там песочница

UPD: добавил пример(TS) на ф-ях

function Timer<T extends {}>(initData: T) {

    let id: number | undefined
    let data: T | undefined

    return (
        foo: (data: T) => void,
        step: number = 1e3
    ) => ({
        initData, foo, step
        , start() {
            if (!data) data = Object.assign(Object.create(null), this.initData)
            if (!id) id = this.gen()
        }
        , stop() {
            clearInterval(id)
            id = undefined
            data = undefined
        }
        , pause() {
            clearInterval(id)
            id = undefined
        }
        , gen(): number {
            return setInterval(() => {
                this.foo(data as any)
            }, this.step)
        }
    })
}

test: {
    const t = Timer({ counter: 0 })(data => {
        data.counter++
        console.log(data.counter)
    })
    test()
    function test() {
        t.start()
        setTimeout(() => {
            t.pause()
            setTimeout(() => {
                t.start()
                setTimeout(() => {
                    t.stop()
                    test()
                }, 3e3)
            }, 3e3)
        }, 5e3)
    }
}

javascript deep clone

data = Object.assign(Object.create(null), this.initData)
data = JSON.parse(JSON.stringify(this.initData))
// ...
3
  • непонятный пример для меня, но спасибо за помощь (не учил еще классы и тд) 29 апр 2020 в 10:23
  • @Roma, перейди по ссылке в самом низу, может понятнее будет.
    – qwabra
    29 апр 2020 в 10:30
  • 1
    @Roma, добавил пример на ф-ях. поможет ли
    – qwabra
    29 апр 2020 в 11:04

Ваш ответ

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

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