SoFunction
Updated on 2025-03-09

How to set countdown using moment in vue

How to set countdown using moment in vue

Method 1

Countdown method is often needed in daily development. Now encapsulate it

//Step 1: Introducing momentimport moment from 'moment';

let nowTime:any = ref('')//Current timelet diffTime:any = ref('')//The difference between the current time and the specified timelet countdown:any = ref(0)//Countdown// Set setInterval to output the current time once a second update countdown timelet interval:any = setInterval(function() {
	//Get the current time according to the time, minute and second format. You need to set the year, month and day as follows: "YYYY-MM-DDD HH:mm:ss"	 = moment().format("HH:mm:ss")
	//Get a second value by comparing the time difference	//Compare the time difference. Compare according to the seconds seconds. If it is a year, month and day comparison, set as the right moment('2024-02-05 10:00:00', 'YYY-MMM-DDD hh:mm:ss')	//moment() is the current time	 = moment('10:00:00', 'hh:mm:ss').diff(moment(), "seconds")
	//Countdown If the countdown is only displayed for the last 5 minutes, let's make a judgment	if(<5*60){
		let h = (, 'seconds').hours()//Hour		let m = (, 'seconds').minutes()//minute		let s = (, 'seconds').seconds()//Second		 = `${h<10?'0'+h:h}:${m<10?'0'+m:m}:${s<10?'0'+s:s}`
	}
	// Determine whether the timer needs to be executed	if( < 0 ){
		clearInterval(interval)//Clear the timer	}
}, 1000);


// Triggered when the page is destroyedonBeforeUnmount(()=>{
	clearInterval(interval)//Clear the timer})

Method 2

Ideas: End time - Current time = remaining seconds;

countDown(end_time) { 
if (end_time == null) return; 
let nowTime = moment() .locale('zh-cn') .format('YYYY-MM-DD HH:mm:ss'); //Current timelet endTime = moment(end_time) .locale('zh-cn') .format('YYYY-MM-DD HH:mm:ss'); 
return moment(endTime).diff(moment(nowTime), 'seconds'); //The remaining countdown seconds},

This is the end of this article about how to set countdown using moment in vue. For more related content on vue moment setting countdown, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!