HarmonyOS 鸿蒙Next中短信验证码发送之后,如何实现60秒倒计时
HarmonyOS 鸿蒙Next中短信验证码发送之后,如何实现60秒倒计时 我这边要实现个功能,就是需要在短信验证码发送之后,实现60秒倒计时,这个大家有搞过吗?
TextTimer组件提供了通过文本显示计时信息并控制其计时器状态的功能。
具体可参考文档:TextTimer-信息展示-ArkTS组件-ArkUI(方舟UI框架)-应用框架 - 华为HarmonyOS开发者 (huawei.com)
也可以看下这个示例demo:
// xxx.ets
@Entry
@Component
struct TextTimerExample {
textTimerController: TextTimerController = new TextTimerController()
@State format: string = 'ss'
build() {
Column () {
TextTimer({ isCountDown: true, count: 60000, controller: this.textTimerController })
.format(this.format)
.fontColor(Color.Black)
.fontSize(50)
.onTimer((utc: number, elapsedTime: number) => {
console.info('textTimer notCountDown utc is:' + utc + ', elapsedTime: ' + elapsedTime)
})
Row () {
Button("start").onClick(() => {
this.textTimerController.start()
})
Button("pause").onClick(() => {
this.textTimerController.pause()
})
Button("reset").onClick(() => {
this.textTimerController.reset()
})
}
}
}
}
更多关于HarmonyOS 鸿蒙Next中短信验证码发送之后,如何实现60秒倒计时的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS鸿蒙Next中实现短信验证码发送后的60秒倒计时,可以使用TaskDispatcher和EventHandler来处理倒计时逻辑。首先,定义一个Runnable任务来更新UI显示倒计时。使用GlobalTaskDispatcher创建一个全局任务分发器,通过delayDispatch方法实现每秒钟执行一次任务。在Runnable中,每秒减少倒计时时间,并更新UI显示剩余时间。当倒计时结束时,停止任务并恢复按钮的可点击状态。具体代码示例如下:
import taskpool from '@ohos.taskpool';
import { GlobalTaskDispatcher } from '@ohos.taskpool';
import { EventHandler, EventPriority } from '@ohos.eventhandler';
let countDownTime = 60;
let isCounting = false;
let timer: taskpool.Task | null = null;
function startCountDown() {
if (isCounting) return;
isCounting = true;
const taskDispatcher = GlobalTaskDispatcher.getGlobalTaskDispatcher();
timer = taskDispatcher.delayDispatch(() => {
countDownTime--;
if (countDownTime > 0) {
// 更新UI显示剩余时间
updateCountDownUI(countDownTime);
startCountDown();
} else {
// 倒计时结束,恢复按钮状态
resetCountDown();
}
}, 1000);
}
function resetCountDown() {
if (timer) {
timer.cancel();
}
countDownTime = 60;
isCounting = false;
// 恢复按钮可点击状态
updateButtonState(true);
}
function updateCountDownUI(time: number) {
// 更新UI显示剩余时间
}
function updateButtonState(enabled: boolean) {
// 更新按钮状态
}
以上代码实现了60秒倒计时的功能,每秒更新一次UI显示剩余时间,并在倒计时结束后恢复按钮的可点击状态。
在HarmonyOS鸿蒙Next中实现短信验证码60秒倒计时,可以通过以下步骤:
- 设置计时器:使用
setTimeout或setInterval方法实现倒计时功能。 - 更新UI:在倒计时过程中,实时更新按钮的显示文本。
- 禁止点击:在倒计时期间,禁用按钮以防止重复发送验证码。
- 恢复按钮:倒计时结束后,重新启用按钮并恢复原始文本。
示例代码:
let countdown = 60;
let timer = setInterval(() => {
if (countdown <= 0) {
clearInterval(timer);
button.setEnabled(true);
button.setText("获取验证码");
} else {
button.setEnabled(false);
button.setText(`${countdown}秒后重试`);
countdown--;
}
}, 1000);
通过这种方式,可以简单高效地实现短信验证码的60秒倒计时功能。

