uniapp 的 js一个小时倒计时

uniapp 的 js一个小时倒计时

timer:"",				//定时器	
isEndTime:"01:00:00",	//倒计时要有个初始值
onLoad(){
	this.timer = setInterval(()=>{
		let allTime = 0;
		let h = this.isEndTime.substring(0,2);
		let m = this.isEndTime.substring(3,5);
		let s = this.isEndTime.substring(6,8);
		allTime = Number(h) * 60 * 60 +  Number(m) * 60  + Number(s);
		if(allTime<=0)return clearInterval(this.timer);//执行倒计时结束逻辑
		allTime --;
		h = parseInt(allTime / 3600) < 10 ? '0' + String(parseInt(allTime / 3600)) : parseInt(allTime / 3600);
		m = parseInt(allTime / 60) < 10 ? '0' + String(parseInt(allTime / 60)) : parseInt(allTime / 60);
		s = allTime % 60 < 10 ? '0' + String(allTime % 60) : allTime % 60;
		this.isEndTime = h+":"+m+":"+s;
	},1000)
}
要在uniapp导航栏中加入倒计时,可以使用定时器和自定义导航栏组件来实现。 首先,在页面的onLoad函数中设置一个定时器,每隔一秒钟更新倒计时时间: ```javascript onLoad: function () { this.setData({ countdown: 60 // 设置倒计时时间 }) // 启动定时器 this.timer = setInterval(() => { let countdown = this.data.countdown - 1 if (countdown < 0) { clearInterval(this.timer) return } this.setData({ countdown: countdown }) }, 1000) } ``` 接着,在自定义导航栏组件中使用倒计时时间来显示倒计时: ```javascript <template> <view class="custom-navbar"> <view class="title">{{title}}</view> <view class="countdown" v-if="countdown >= 0">{{countdown}}s</view> </view> </template> <script> export default { name: 'CustomNavbar', props: { title: { type: String, default: '' }, countdown: { type: Number, default: -1 } } } </script> <style> .custom-navbar { display: flex; justify-content: space-between; align-items: center; height: 44px; padding: 0 15px; background-color: #fff; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2); } .title { font-size: 16px; font-weight: bold; } .countdown { font-size: 14px; color: #666; } </style> ``` 最后,在页面中使用自定义导航栏组件,并将倒计时时间传递给组件: ```javascript <template> <view class="container"> <custom-navbar title="页面标题" :countdown="countdown" /> <!-- 页面内容 --> </view> </template> <script> import CustomNavbar from '@/components/CustomNavbar' export default { components: { CustomNavbar }, data () { return { countdown: 60 } }, onLoad: function () { // 启动定时器 this.timer = setInterval(() => { let countdown = this.countdown - 1 if (countdown < 0) { clearInterval(this.timer) return } this.countdown = countdown }, 1000) } } </script> ``` 这样,在导航栏中就可以显示倒计时了。需要注意的是,在页面销毁时要清除定时器,否则会导致内存泄漏。可以在onUnload函数中清除定时器: ```javascript onUnload: function () { clearInterval(this.timer) } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值