diff --git a/BackgroundTimerExample.tsx b/BackgroundTimerExample.tsx new file mode 100644 index 0000000000000000000000000000000000000000..d5724591ceb0c1916dc7d638151184de9fd1ce67 --- /dev/null +++ b/BackgroundTimerExample.tsx @@ -0,0 +1,171 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. All rights reserved. +* +* Use of this source code is governed by a MIT license that can be +* found in the LICENSE file +* +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* https://github.com/ocetnik/react-native-background-timer/blob/master/LICENSE +* +*/ + +import {View, Button, StyleSheet, Text,TextInput} from 'react-native'; +import React, {useState} from 'react'; +import BackgroundTimer from "react-native-background-timer"; +export function BackgroundTimerExample() { + let [count, setCount] = useState(0); + let [text, setText] = useState(""); + // BackgroundTimer延时 + let [delay, setDelay] = useState("1000"); + // setTimeout延时 + let [timeoutDelay, setTimeoutDelay] = useState("1000"); + // setInterval延时 + let [intervalDelay, setIntervalDelay] = useState("1000"); + let timeoutList:number[] = [] + let [intervalList, setIntervalList] = useState([]); + + // runBackgroundTimer + function onPressStart(){ + setText("开启定时器...") + BackgroundTimer.runBackgroundTimer(()=>{ + setCount(count+=1) + },parseInt(delay)) + } + function onPressStop(){ + setText("结束定时器") + BackgroundTimer.stopBackgroundTimer() + } + + // setTimeout + function setTimeoutStart(){ + setText("开启定时器...") + let timeoutId = BackgroundTimer.setTimeout(()=>{ + setCount(count+=1) + },parseInt(timeoutDelay)) + timeoutList.push(timeoutId) + } + function setTimeoutStop(){ + setText("结束定时器") + if(timeoutList.length>0){ + BackgroundTimer.clearTimeout(timeoutList[0]) + timeoutList.shift() + } + } + + // setInterval + function setIntervalStart(){ + setText("开启定时器...") + let intervalId = BackgroundTimer.setInterval(()=>{ + setCount(count+=1) + },parseInt(intervalDelay)) + setIntervalList([...intervalList,intervalId]) + } + function setIntervalStop(){ + setText("结束定时器") + if(intervalList.length>0){ + BackgroundTimer.clearInterval(intervalList[0]) + intervalList.shift() + } + } + function resetNumber(){ + setCount(0) + setText("") + } + return ( + + + +