DEV Community

HarmonyOS
HarmonyOS

Posted on

Random Number Generation with Math API

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() and clearInterval() usage
  • Math API: Especially Math.random() for generating random values
  • UI Components: Text, Progress, Column from ArkUI

Implementation Steps

  1. Import required modules
  2. Define state variables
  3. Create your function with Math API
  4. 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'
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

Step 3 : Generate 6-digit random number with Math API

  generateSixDigitNumber(): string {
    const randomNum = Math.floor(100000 + Math.random() * 900000);
    return randomNum.toString();
  }
Enter fullscreen mode Exit fullscreen mode

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);
  }
Enter fullscreen mode Exit fullscreen mode

Step 5 : Clear Interval

  aboutToDisappear() {
    if (this.intervalId !== undefined) {
      clearInterval(this.intervalId);
      this.intervalId = undefined;
    }
  }
Enter fullscreen mode Exit fullscreen mode

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)
  }
}
Enter fullscreen mode Exit fullscreen mode

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.

Written by Egemen Ayhan

Top comments (0)