Home WeChat Applet WeChat Development WeChat public account development to implement a countdown function (pure code)

WeChat public account development to implement a countdown function (pure code)

Jul 27, 2018 pm 04:35 PM
android iphone javascript

The following is a code I wrote myself. The function is to implement countdown during the development process of WeChat public account. The effect is as follows, the order has been submitted, please complete the payment within 2 minutes and 57 seconds. Pure code analysis.

WeChat public account development to implement a countdown function (pure code)

#The initial idea did not consider the situation of the page running in the background and locking the screen. The code is as follows:

let interval = setInterval(() => {
            let {staticTime} = this.state;
            staticTime = staticTime - 1;
            if (staticTime <= 0) {
                clearInterval(interval);
                this.setState({
                    tip:&#39;支付超时&#39;,
                    staticTime:0
                });
                return;
            }
            let minutes = parseInt(staticTime/60);
            let Seconds = staticTime%60;
            let tip = &#39;订单已提交,请在&#39;+minutes+&#39;分&#39;+Seconds+&#39;秒内完成支付&#39;;
            this.setState({
                tip:tip,
                staticTime:staticTime 
            });
        }, 1000);
后来测试发现锁屏或者把页面留在后台,计算就不对,于是把代码进行了如下改造。



  let interval = setInterval(() => {
            let {backGroundTime, staticTime} = this.state;
            this.setState({
                backGroundTime:0
            });
            staticTime = staticTime - backGroundTime - 1; 
            if (staticTime <= 0) {
                clearInterval(interval);
                this.setState({
                    tip:&#39;支付超时&#39;,
                    staticTime:0,
                });
                return;
            }
            let minutes = parseInt(staticTime/60);
            let Seconds = staticTime%60;
            let tip = &#39;订单已提交,请在&#39;+minutes+&#39;分&#39;+Seconds+&#39;秒内完成支付&#39;;
            this.setState({
                tip:tip,
                staticTime:staticTime,
            });
        }, 1000);
        this.listenPageShowHideHandle();
    
     //计算页面在后台的时间
Copy after login

listenPageShowHideHandle = () =>{

let {backGroundTime} = this.state;
let start, end;
let self = this;
document.addEventListener("visibilitychange", function() {
    if(document.visibilityState == &#39;hidden&#39;){
        start = new Date().getTime();
    }else if(document.visibilityState == &#39;visible&#39;){
        end = new Date().getTime();
        backGroundTime = Math.floor((end - start)/1000);
        self.setState({backGroundTime});
        console.log(&#39;时间差:&#39;, backGroundTime);
    }
    console.log( document.visibilityState );
});
Copy after login

}

改造之后发先问题依然存在。原因是:
You cannot continue to run javascript while the iPhone is sleeping using setTimeout(), however.When the phone is put to sleep, Safari will kill any running javascript processes using setTimeout(). Check out this answer here for some reasons why this is done.

**解决方案:**
订单生成的时候我们记录下这个时间为A, 时间间隔为B(3分钟内需要付款,B为3*60*1000),C为现在的时间。我们使用setInterval 每个1秒读取一下时间。那么倒计时时间 == A+B-C,代码如下

 let interval = setInterval(()=>{
        let {orderTime, staticTime} = this.state;
        let nowTime = Date.now();
        let sub = Math.floor((orderTime + staticTime - nowTime)/1000);
        console.log(&#39;sub&#39;,sub);
        if(sub<=0){
            clearInterval(interval);
            this.setState({
                tip:&#39;支付超时&#39;,
                isFalse:true
            });
            return;
        }
        let minutes = parseInt(sub/60);
        let Seconds = sub%60;
        let tip = &#39;订单已提交,请在&#39;+minutes+&#39;分&#39;+Seconds+&#39;秒内完成支付&#39;;
        console.log(tip);
        this.setState({
            tip:tip,
            isFalse:false
        });
    },1000);
Copy after login

apache php mysql

Related articles:

WeChat public account authorization settings, WeChat public authorization

WeChat public account clicks the menu to open and log in to the microsite implementation method

Related Video:

Chuanzhi and Dark Horse WeChat public platform development video tutorial

The above is the detailed content of WeChat public account development to implement a countdown function (pure code). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Xiaomi Redmi Note 14 Pro Plus arrives as first Qualcomm Snapdragon 7s Gen 3 smartphone with Light Hunter 800 camera Xiaomi Redmi Note 14 Pro Plus arrives as first Qualcomm Snapdragon 7s Gen 3 smartphone with Light Hunter 800 camera Sep 27, 2024 am 06:23 AM

The Redmi Note 14 Pro Plus is now official as a direct successor to last year'sRedmi Note 13 Pro Plus(curr. $375 on Amazon). As expected, the Redmi Note 14 Pro Plus heads up the Redmi Note 14 series alongside theRedmi Note 14and Redmi Note 14 Pro. Li

Oppo Find X8 design looks like a cross between Apple iPhone 16 Pro and OnePlus Open in early images Oppo Find X8 design looks like a cross between Apple iPhone 16 Pro and OnePlus Open in early images Sep 28, 2024 am 06:04 AM

Historically, Oppo has refreshed its flagship 'Find X' series in late winter or early spring, save for the original Find X that it announced in June 2018. To that end, the Find X7 and Find X7 Ultra are barely more than six months old at this point. H

Gate.io trading platform official app download and installation address Gate.io trading platform official app download and installation address Feb 13, 2025 pm 07:33 PM

This article details the steps to register and download the latest app on the official website of Gate.io. First, the registration process is introduced, including filling in the registration information, verifying the email/mobile phone number, and completing the registration. Secondly, it explains how to download the Gate.io App on iOS devices and Android devices. Finally, security tips are emphasized, such as verifying the authenticity of the official website, enabling two-step verification, and being alert to phishing risks to ensure the safety of user accounts and assets.

How to solve the problem of 'Undefined array key 'sign'' error when calling Alipay EasySDK using PHP? How to solve the problem of 'Undefined array key 'sign'' error when calling Alipay EasySDK using PHP? Mar 31, 2025 pm 11:51 PM

Problem Description When calling Alipay EasySDK using PHP, after filling in the parameters according to the official code, an error message was reported during operation: "Undefined...

iQOO Z9 Turbo+ debuts as Dimensity 9300+ smartphone with \'off-the-charts\' battery life iQOO Z9 Turbo+ debuts as Dimensity 9300+ smartphone with \'off-the-charts\' battery life Sep 26, 2024 am 06:20 AM

TheZ9 Turbo+has now been unleashed on Vivo's online Chinese store at 2,199 yuan (~$313) for a 12GB RAM/256GB internal storage base model, whereas theRedmiK70 Extreme Editionstarted at 2,599 yuan (~$370) with the same configuration: in fact, its newiQ

Anbi app official download v2.96.2 latest version installation Anbi official Android version Anbi app official download v2.96.2 latest version installation Anbi official Android version Mar 04, 2025 pm 01:06 PM

Binance App official installation steps: Android needs to visit the official website to find the download link, choose the Android version to download and install; iOS search for "Binance" on the App Store. All should pay attention to the agreement through official channels.

Lenovo reveals new color option for the 2024 Legion Y700 gaming tablet Lenovo reveals new color option for the 2024 Legion Y700 gaming tablet Sep 29, 2024 am 06:05 AM

Lenovo is gearing up to launch the 2024 Legion Y700 on September 29 in China. This new Android gaming tablet will be going against the RedMagic Nova, and the company has already confirmed almost all the specs of the device. Now, hours before the full

Download link of Ouyi iOS version installation package Download link of Ouyi iOS version installation package Feb 21, 2025 pm 07:42 PM

Ouyi is a world-leading cryptocurrency exchange with its official iOS app that provides users with a convenient and secure digital asset management experience. Users can download the Ouyi iOS version installation package for free through the download link provided in this article, and enjoy the following main functions: Convenient trading platform: Users can easily buy and sell hundreds of cryptocurrencies on the Ouyi iOS app, including Bitcoin and Ethereum. and Dogecoin. Safe and reliable storage: Ouyi adopts advanced security technology to provide users with safe and reliable digital asset storage. 2FA, biometric authentication and other security measures ensure that user assets are not infringed. Real-time market data: Ouyi iOS app provides real-time market data and charts, allowing users to grasp encryption at any time

See all articles