WeChat applet function: how to generate seven different random integers at the same time, the number range is 1-35 (inspiration: double color ball)

Functional description

同时生成七个不相同的随机数字,当点击开始,数字开始变化,变化时间为0.3秒,当点击结束,数字停止。

Implementation steps

  • First, define a function, the function is: generate seven different numbers, and the number range is 1-35, and the type is an integer.
  • Second, define the start event. The start event uses the setInterval timer, and the time is 300ms, that is, the function that generates numbers is called every 300ms.
  • Third, define the end end time. Click on the end time and the numbers stop.

Code

// pages/second/second.js
Page({
    
    

  /**
   * 页面的初始数据
   */
  data: {
    
    
    nameValue:'',
    randomNumbers: [], // 存储随机数字的数组
    intervalId: null, // 存储定时器 ID
    isRandoming: false, // 记录是否正在生成随机数字
  },
  /* // 生成七个不相等的随机数字 */
  generateRandomNumbers() {
    
    
    let numbers = [];
    while (numbers.length < 7) {
    
    
      const num = Math.floor(Math.random() * 49) + 1;
      if (numbers.indexOf(num) === -1) {
    
    
        numbers.push(num);
      }
    }
    return numbers;
  },

  // 开始生成随机数字
  start() {
    
    
    this.setData({
    
    
      nameValue:''
    })
    // 如果正在生成随机数字,则直接返回
    if (this.data.isRandoming) {
    
    
      return;
    }
    // 开始生成随机数字并设置定时器
    const intervalId = setInterval(() => {
    
    
      const numbers = this.generateRandomNumbers();
      this.setData({
    
    
        randomNumbers: numbers,
      });
    }, 300);
    this.setData({
    
    
      intervalId: intervalId,
      isRandoming: true,
    });
  },
  // 停止生成随机数字
  end() {
    
    
    // 如果没有在生成随机数字,则直接返回
    if (!this.data.isRandoming) {
    
    
      return;
    }
    // 清除定时器并重置状态
    clearInterval(this.data.intervalId);
    this.setData({
    
    
      intervalId: null,
      isRandoming: false,
    });
  },

//wxml
//数据显示
<view wx:for="{
     
     {randomNumbers}}" wx:key="index">{
   
   {item}}</view>
//开始
<button bindtap="start">开始</button>
//结束时间
<button bindtap="end">结束</button>

Guess you like

Origin blog.csdn.net/weixin_52312427/article/details/129509138