Nayeem M. Muzahid
Nayeem M. Muzahid

Reputation: 139

How can I make multiple countdown timer with one countdown library?

I am trying to create multiple countdown by using one countdown library but when I loop through the elements, only the last countdown works. Other countdown stays still. The interval is only working for the last printed countdown.

I have tried this. but it only works for the last item of the array. How do I make the timer work for all the items?

<script>

 

    let q = [
        {
            el: '.countdown',
            endt: '1 Jan, 2025'
        },
        {
            el: '.countdown2',
            endt: '1 Jan, 2024'
        }
    ]

    q.map((item) => {
        Countdown.init(item.el, {
        startTime: new Date(Date.now()),
        endTime: item?.endt,
        untill: 'tillMonth',
        timeLabel: {
            month: 'Months',
            day: 'Days',
            hour: 'Hours',
            minute: 'Minutes',
            second: 'Seconds'
        }
    });
    })
    
    
</script>

This is what does the init function looks like which is creating the countdown.

function init(targetElementId, config) {
        let { startTime, endTime, untill, timeLabel } = config;
        tillWhen = untill;
        targetStartDate = new Date(startTime);
        targetEndDate = new Date(endTime);
        labels = timeLabel;
        targetElement = document.querySelector(targetElementId);
        if (!targetElement) {
            console.error("Target element not found.");
            return;
        }

        currentDate = new Date(Date.now());

        if(currentDate >= targetStartDate && currentDate <= targetEndDate){
            updateCountdown();
            setInterval(updateCountdown, 1000);
        }
        
        
    }

Upvotes: 0

Views: 53

Answers (0)

Related Questions