LWC 화면에 남은 시간 표시하기 (setInterval)

ahncheer·2022년 10월 20일
0

LWC & LWR

목록 보기
20/45

● 결과화면 미리보기

● 코드 작성
※ lwc024UseTimer.html

<template>
    <div class="wrapper">
        <button onclick={timeBtnClick} class="custom-btn">Click !</button>
        <p class="time-msg" lwc:dom="manual"></p>
    </div>
</template>

※ lwc024UseTimer.js

import { LightningElement, track } from 'lwc';

export default class Lwc024UseTimer extends LightningElement {
    @track timer;
    @track timerTime = {minute : 0, sec : 10};
    @track timeArea;

    renderedCallback() {
        //남은 시간을 표시해줄 영역 지정
        this.timeArea = this.template.querySelector(".time-msg");
        console.log('this.timeArea : ', this.timeArea);
    }

    // Click 버튼을 클릭했을 때
    timeBtnClick(){
        console.log('timeBtnClick ');
        this.timeArea.innerHTML = '';
        clearInterval(this.timer);
        //Timer 설정 
        this.timerTime = {minute : 0, sec : 10};
        setTimeout(() => {
            this.setTimerMsg();
        }, 100);
    }

    // 남은 시간 계산해서 표시해주는 부분
    setTimerMsg() {
        if (this.timeArea) {
            clearInterval(this.timer);
            this.timer = setInterval(() => {
                if (this.timerTime.sec == '00') {
                    if (this.timerTime.minute > 0) {
                        this.timerTime.minute--;
                    }
                    this.timerTime.sec = 60;
                }
                this.timerTime.sec--;
                this.timeArea.innerHTML = 'Timer →  ' 
                                + (this.timerTime.minute < 10 ? '0'+this.timerTime.minute : this.timerTime.minute) + ":"
                                + (this.timerTime.sec < 10 ? '0'+ this.timerTime.sec : this.timerTime.sec);
                if (this.timerTime.minute === 0 && this.timerTime.sec === 0) {
                    clearInterval(this.timer);
                }
            }, 1000);
        }
    }
}

타이머 시간을 10초로 설정했습니다

※ lwc024UseTimer.css

.wrapper{
    width: 100%;
    max-width: 800px;
    margin: 10px auto;
    background-color: #cfcceb;
    padding: 20px 10px;
    border-radius: 5px;
    min-height: 200px;
    box-shadow: rgb(99 99 99 / 20%) 0px 2px 8px 0px;
}
.wrapper .custom-btn{
    background-color: #f0f2f5;
    border: 1px solid #d1d7df;
    border-radius: 10px;
    font-size: 15px;
    color: #636363;
    padding: 15px 40px;
}

● 결과 화면 확인

profile
개인 공부 기록용.

0개의 댓글