Read the original article:Random Number Generation with Math API
Requirement Description
This article demonstrates how to implement a time-based random number generator in a HarmonyOS application using the Math API. The application generates a six-digit number that updates every 30 seconds. A ring-shaped progress bar visualizes the countdown.
Use cases include:
- Temporary passcodes
- In-app authentication tokens
- Dynamic security visuals
Background Knowledge
To follow this tutorial, you should be familiar with the following:
-
ArkTS Basics: Component structure and state management (
@State) -
Timers in ArkTS:
setInterval()andclearInterval()usage -
Math API: Especially
Math.random()for generating random values -
UI Components:
Text,Progress,Columnfrom ArkUI
Implementation Steps
- Import required modules
- Define state variables
- Create your function with Math API
- Build app's UI
Code Snippet / Configuration
Step 1 : Import required modules
import { Progress, Text, Column } from '@kit.ArkUI'
import { Color, FontWeight } from '@kit.ArkUI'
import { Component } from '@kit.ComponentKit'
Step 2 : Define component and state variables
@Component
export default struct RandomNumberComponent {
@State randomValue: string = '000000';
@State seconds: number = 0;
private intervalId: number | undefined = undefined;
Step 3 : Generate 6-digit random number with Math API
generateSixDigitNumber(): string {
const randomNum = Math.floor(100000 + Math.random() * 900000);
return randomNum.toString();
}
Step 4 : Update the random number every 30 seconds
aboutToAppear() {
this.randomValue = this.generateSixDigitNumber();
this.intervalId = setInterval(() => {
this.seconds += 1;
if (this.seconds >= 30) {
this.seconds = 0;
this.randomValue = this.generateSixDigitNumber();
}
}, 1000);
}
Step 5 : Clear Interval
aboutToDisappear() {
if (this.intervalId !== undefined) {
clearInterval(this.intervalId);
this.intervalId = undefined;
}
}
Step 6 : Build UI structure
build() {
Column() {
Progress({ value: this.seconds, total: 30, type: ProgressType.Ring })
.width(40)
.style({ enableScanEffect: true })
.color(Color.Red)
Text('Your 6-digit random number:')
.fontSize(12)
.margin({ top: 10, bottom: 10 })
Text(this.randomValue)
.fontSize(32)
.fontWeight(FontWeight.Bold)
.fontColor(Color.Red)
.margin({ bottom: 10 })
Text('(It changes every 30 seconds)')
.fontSize(10)
.fontColor(Color.Grey)
}.padding(20)
}
}
Test Results
Using the native Math API along with basic state management and timer functions, this component allows developers to generate secure, timed, and user-friendly random values. This is especially useful in security-sensitive applications like OTP generators and temporary codes. With a simple UI and clear logic flow, this structure is a great foundation for more advanced token systems.
Top comments (0)