Reusable animation control method based on behavior pattern

By adopting a reusable animation control method based on behavior patterns, the difficulties in reusing animation control methods and the rigid configuration problems in mini-program development are solved. This enables cross-scenario reuse and flexible configuration of animation logic, improves the running stability and lightweight characteristics of mini-program animations, and adapts to diverse business scenario requirements.

CN122064337APending Publication Date: 2026-05-19BEIJING DISCOVERY CORNER TECH CO LTD
View PDF 6 Cites 0 Cited by

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
BEIJING DISCOVERY CORNER TECH CO LTD
Filing Date
2025-12-25
Publication Date
2026-05-19

AI Technical Summary

Technical Problem

In mini-program development, existing animation control methods suffer from problems such as difficulty in reuse, insufficient configuration flexibility, complex resource management, lack of state tracking, and insufficient robustness, making it difficult to meet the needs of diverse business scenarios.

Method used

It adopts a reusable animation control method based on behavior patterns. By encapsulating general animation behavior modules, it enables the reuse of animation logic across pages/components, supports flexible configuration in multiple dimensions and precise control throughout the entire lifecycle, has state traceability and fault tolerance and adaptive capabilities, and is built in conjunction with the native behavior mechanism of WeChat Mini Programs to adapt to various business scenarios such as product list loading and countdown scrolling.

Benefits of technology

It enables cross-scene reuse of animation logic, improves configuration flexibility and scalability, ensures the stability and lightweight nature of animation operation, reduces development and maintenance costs, and supports diverse animation effects and business scenario adaptation.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122064337A_ABST
    Figure CN122064337A_ABST
Patent Text Reader

Abstract

The invention discloses a reusable animation control method based on a behavior mode. The reusable animation control method is suitable for an applet development scene. According to the method, animation logic cross-page / component multiplexing is realized by packaging a universal animation behavior module, and the module supports 12 types of parameter configuration, is compatible with static values, dynamic functions and responsive data, and can be matched with a preset template to quickly adapt to various scenes. According to the method, multi-element batch animation is realized through timer sequence closed-loop management, full life cycle control of starting, pausing, resetting and recovering is provided, and key node callback and real-time state query are supported. A fault-tolerant adaptive mechanism is built in, animation strategies can be dynamically adjusted to cope with performance bottlenecks and abnormal scenes, and meanwhile, automatic resource cleaning logic is integrated to avoid memory leakage. Light weight and expansibility are considered, the problems that a traditional scheme is difficult to reuse, rigid in configuration, disordered in management and the like are solved, and development efficiency and user experience are improved.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of animation control methods, and more particularly to a reusable animation control method based on behavior patterns. Background Technology

[0002] In mobile application development, animation is a key means to enhance user experience, especially in the context of mini-program development, where animation can effectively optimize interactive feedback and interface presentation. However, due to the limitations of the mini-program framework, animation implementation and management face many core issues: the strong independence of pages and components makes it difficult to reuse animation logic; the fact that most parameters are hard-coded makes configuration inflexible; the need for manual management of resources such as timers can easily lead to leaks; and the lack of a unified state tracking and lifecycle management mechanism.

[0003] Existing animation implementation solutions all have obvious limitations and are difficult to adapt to actual needs: Directly writing animation code: requires repeating the complete logic on each page / component, resulting in severe code redundancy and extremely high costs for subsequent modification and maintenance; Introducing third-party animation libraries will significantly increase the size of the mini-program package, which conflicts with the core characteristics of mini-programs being "lightweight and efficient", and some functions have poor compatibility. Utility function encapsulation: It only enables basic code reuse, lacks automatic linkage with page / component lifecycle, has no unified control interface and status query capability, and has insufficient extensibility; Animation components in React / Vue frameworks rely on specific underlying mechanisms of the framework, cannot be directly adapted to mini-programs, and have high adaptation and modification costs and are prone to compatibility issues. Mini Program native Behavior mechanism: Existing animation-related implementations have obvious defects. Hard-coded configuration parameters lead to poor adaptability. It only supports simple show / hide functions and lacks unified lifecycle management, status query, callback extension and multi-element batch control capabilities, making it difficult to meet the needs of diverse business scenarios.

[0004] Based on this, we propose a reusable animation control method based on behavior patterns. Summary of the Invention

[0005] To address the technical challenges of existing animation control methods in WeChat Mini Program development, such as difficulties in reuse, insufficient configuration flexibility, complex resource management, lack of state tracking, and insufficient robustness, this invention provides a reusable animation control method based on behavior patterns. This method encapsulates general animation behavior modules to achieve cross-page / component reuse of animation logic, supports multi-dimensional flexible configuration and precise control throughout the entire lifecycle, and also possesses state traceability and fault-tolerant adaptive capabilities, while balancing lightweight characteristics and functional scalability.

[0006] This invention is achieved using the following technical solution: a reusable animation control method based on behavior patterns, comprising the following steps: Step S1: Create an animation behavior module. This module encapsulates general animation logic and defines parameter interfaces for configuring animation effects, animation control methods, lifecycle hook functions, and status query interfaces. The animation behavior module is pre-configured with preset configuration templates suitable for different scenarios and integrates resource cleanup logic to avoid memory leaks.

[0007] Step S2: Import the animation behavior module into the target page or component, allowing it to inherit the module's data, methods, and lifecycle; after importing, the target page / component can directly call the relevant functions without having to rewrite the basic animation logic.

[0008] Step S3: Receive the configuration object provided by the user through the parameter interface. This configuration object includes at least one or more parameters such as the target element quantity, element display interval time, and animation auto-start flag. It may also include extended parameters such as animation delay execution time, whether to loop the animation, number of loops, animation execution direction, whether to enable debug mode, animation easing function type, data field name for storing element state, base CSS class name, and display state CSS class name. The user can generate a configuration object by specifying the name of a preset configuration template and selectively overriding some of its parameters. At least one parameter in the configuration object can be a dynamic function or reactive data. The dynamic function can dynamically calculate parameter values ​​based on element index, animation progress, or external data to achieve non-linear sequence animation effects. Merge and verify the user configuration with the default configuration defined in the module to generate the final running configuration. During parameter verification, key parameters are validated for validity. Invalid parameters will be automatically replaced with default values ​​to ensure the legality of the configuration.

[0009] Step S4: Based on the final runtime configuration, within the lifecycle of the animation behavior module, a timer sequence is automatically managed through its internally encapsulated animation execution logic to control the display state of multiple target elements sequentially or in parallel, achieving batch animation effects; specifically including: Step S4.1: Based on the number of target elements in the final running configuration, initialize a state array to track the display status of each element; Step S4.2: Based on the element display interval, calculate the timer trigger point corresponding to each element, and create the corresponding timer task to form a timer sequence; Step S4.3: Execute timer tasks sequentially according to the timer sequence. When each task is executed, update the display state of the corresponding element in the state array and trigger the view layer update of the mini-program framework. Step S4.4: If a pause or reset command is received during animation execution, immediately clear all timer tasks that have not yet been executed, and update the animation status according to the command.

[0010] Step S5: During animation execution, in response to external calls or internal lifecycle triggers, execute animation control methods. These control methods include at least start, pause, and reset, as well as a resume operation. The "pause" operation specifically includes: clearing currently unexecuted timer tasks; serializing and saving the complete state of the animation, which includes the list of elements that have been displayed, the current progress, the time consumed, and the current configuration parameters; and the "resume" operation calculates the remaining animation sequence based on the saved complete state and continues the animation execution from the paused node.

[0011] Step S6: Trigger preset callback functions at different stages of animation execution, specifically including: triggering the first type of callback function when a single element is displayed and passing the index of the currently displayed element as a parameter to the function; triggering the second type of callback function when all element animation sequences are executed; triggering the third type of callback function when the animation is reset to the initial state; and achieving flexible linkage between animation and business logic through callback functions.

[0012] Step S7: Obtain and return the current running status of the animation, the number of elements that have been completed, and the total progress information in real time through the status query interface; specifically, return a status object containing the following fields: status: a string representing the current status of the animation, whose value includes "not started", "running", "paused", "completed", or "reset"; currentIndex: an integer value representing the index of the most recently completed element; progress: a floating-point value representing the overall progress of the animation, which is obtained by calculating the number of currently completed elements divided by the total number of elements.

[0013] The method also includes animation fault tolerance and adaptive steps: real-time monitoring of the frame rate or system resource usage of the mini-program page; when a performance bottleneck is detected, automatically reducing the animation execution frequency or skipping non-critical frames to ensure page smoothness; when the target element is detected to be missing or the configuration parameters are invalid, executing a predefined degradation scheme to avoid program errors.

[0014] As a further optimization of the present invention, the animation behavior module is built based on the Behavior mechanism of WeChat Mini Programs. It can be introduced and reused by any Mini Program page or component without modifying the original page logic. It is suitable for various business scenarios such as product list loading, countdown scrolling, and pop-up entry, while taking into account both lightweight characteristics and functional scalability. This optimization solution ensures module compatibility and integration convenience by relying on the mature native mechanism of Mini Programs, which greatly reduces development costs and expands the scope of applicable scenarios.

[0015] As a further optimization of the present invention, the parameter merging and verification process in step S3 specifically includes: after receiving the user configuration, first verifying the validity of key parameters, and then deeply merging the user configuration with the built-in default configuration, with the user configuration parameters having higher priority than the default configuration; when initializing the element state, checking whether the corresponding fields in the page / component data meet the requirements, and creating a default state array if they do not; after saving the configuration, if debug mode is enabled, outputting the initialization log, and if an automatic startup flag is configured, delaying the animation startup for a specified time; this optimization scheme ensures the accuracy of the configuration and the reliability of the initialization through a standardized parameter processing flow, while providing debugging support to facilitate troubleshooting.

[0016] As a further optimization of the present invention, the timer sequence management in step S4 adopts a "creation-execution-cleanup" closed-loop mechanism. Before creation, old timers are cleaned up to avoid repeated execution. During execution, the animation running status is checked twice to ensure the effectiveness of the operation. When receiving control commands, unexecuted tasks are cleaned up and the status is updated in a timely manner. This optimization effectively avoids timer leakage and animation chaos, and ensures the orderliness and stability of batch animation execution.

[0017] As a further optimization of the present invention, the animation control method covers the entire lifecycle operation of start, pause, reset, and resume. When starting, it performs pre-verification and resource preparation; when pausing, it serializes and saves the complete state; when resetting, it restores the initial state and triggers a callback; and when resuming, it accurately resumes playback based on the saved state. This optimization scheme realizes fine-grained control of animation, meets the flexible operation requirements in complex interactive scenarios, and ensures the continuity of state switching.

[0018] As a further optimization of the present invention, the callback function adopts a classification triggering mechanism, which accurately triggers the corresponding callback according to the key nodes of the animation execution, and supports users to realize personalized business logic extension based on the callback, such as adding a label after a single element is displayed, unlocking functions after all animations are completed, etc. This optimization scheme decouples the animation logic from the business logic, and improves the scalability and flexibility of the method.

[0019] As a further optimization of the present invention, the status query interface returns a standardized status object, which updates the animation status, element index and progress information in real time. This allows developers to implement debugging and monitoring or page interaction logic linkage based on the status data, such as displaying a loading bar based on the progress. This optimization makes the animation running status traceable, improving development and debugging efficiency and user interaction experience.

[0020] As a further optimization of the present invention, the animation fault tolerance and adaptive mechanism dynamically adjusts the animation execution strategy by monitoring the system performance and operating status in real time, and takes optimization and degradation measures for performance bottlenecks and abnormal scenarios respectively. This optimization scheme significantly improves the robustness of the method, ensures that the animation runs stably under different devices and abnormal scenarios, and avoids program errors affecting the overall function.

[0021] As a further optimization of the present invention, the configuration object supports three configuration methods: static parameters, dynamic functions, and responsive data. The dynamic function can dynamically calculate parameter values ​​based on element index, animation progress, etc., to achieve complex animation effects such as accelerated sequences and non-linear transitions. This optimization scheme greatly improves the configuration flexibility, breaks through the limitations of traditional fixed parameters, and meets the diverse animation effect requirements.

[0022] As a further optimization of the present invention, the animation behavior module has built-in resource cleanup logic. When the detached lifecycle of the mini-program page / component is triggered, all timers are automatically cleaned up and data references are released. At the same time, manual calls to the cleanup interface are also supported. This optimization ensures that the animation resources are synchronized with the lifecycle of the page / component, completely avoids memory leaks, and ensures the running performance of the mini-program.

[0023] Compared with the prior art, the beneficial effects of the present invention are as follows: 1. This invention achieves the core advantage of "write once, use everywhere" by encapsulating a general animation behavior module. The module is built on the native Behavior mechanism of WeChat Mini Programs and can be introduced into any page or component without intrusion, without modifying the original code structure. It automatically inherits the module's data, methods, and lifecycle, completely solving the problems of repetitive animation logic writing and severe code redundancy in traditional solutions. This significantly reduces development and maintenance costs while maintaining the lightweight characteristics of WeChat Mini Programs and avoiding the package size expansion problems caused by third-party libraries.

[0024] 2. This invention supports multi-dimensional flexible configuration and multiple behavior combinations. The configuration objects cover 12 types of core parameters, are compatible with static values, dynamic functions, and reactive data, and, together with preset scene templates and parameter overriding mechanisms, can quickly adapt to diverse business scenarios such as product fade-in and countdown scrolling. Dynamic functions can dynamically calculate parameter values ​​based on element index and animation progress, breaking through the limitations of traditional fixed parameters and realizing complex animation effects such as non-linear sequences, greatly improving the flexibility of animation configuration and scene adaptability.

[0025] 3. This invention achieves automated management and precise control of the entire animation lifecycle. Through a built-in timer sequence "creation-execution-cleanup" closed-loop mechanism, it automatically handles resource allocation and recycling, and combined with page / component lifecycle linkage, completely avoids timer leaks. It also provides complete control methods such as start, pause, reset, and resume. When paused, the state is serialized and saved; when resumed, playback is precisely continued. Combined with a real-time status query interface, the animation's running status is traceable and its operation is controllable, meeting the needs of complex interactive scenarios.

[0026] 4. This invention possesses robust fault tolerance, adaptive capabilities, and scalability. By monitoring page frame rate and system resources in real time, it dynamically adjusts animation execution strategies, automatically optimizes when performance bottlenecks occur, and executes degradation solutions in abnormal scenarios to ensure stable program operation. The categorized callback mechanism decouples animation from business logic, supports personalized feature extensions, and includes built-in automatic resource cleanup logic and a debugging mode. It balances operational stability, development convenience, and functional scalability, significantly improving development efficiency and user experience. Attached Figure Description

[0027] Figure 1 This is a schematic diagram of the core components of the overall technical solution of the present invention; Figure 2 This is a detailed schematic diagram illustrating the configuration object of the core data structure of this invention; Figure 3 This is a schematic diagram of the configuration management process of the present invention; Figure 4 This is a flowchart of the animation execution process of the present invention; Figure 5 This is a schematic diagram of the callback function type of the present invention; Figure 6 This is a complete flowchart of the use of the present invention. Detailed Implementation

[0028] The present invention will now be further described in conjunction with the accompanying drawings and specific embodiments. It should be noted that, without conflict, the various embodiments or technical features described below can be arbitrarily combined to form new embodiments.

[0029] Example 1: Please combine Figures 1-6 This embodiment proposes a reusable animation control method based on behavior patterns, applicable to mobile application development frameworks such as WeChat Mini Programs. Its core functionality addresses the problems of difficult reuse, rigid configuration, and chaotic management in traditional animation implementations by encapsulating general animation behavior modules, flexibly configuring parameters, and automating lifecycle management and state tracking. The specific implementation process is described in detail below. I. Prerequisites for Overall Implementation This implementation method builds an animation behavior module based on the WeChat Mini Program's Behavior mechanism. This module can be imported and reused by any Mini Program page or component without modifying the original page logic. It adapts to various business scenarios such as product list loading, countdown scrolling, and pop-up entry, balancing lightweight characteristics with functional scalability. The overall module architecture is divided into four layers, each with clearly defined responsibilities and collaborative work: The usage layer, namely the Page / Component of the mini-program, integrates animation functions by importing the Behavior module and calling related methods, without needing to concern themselves with the underlying implementation logic; Behavior layer: As the core bridge, it encapsulates animation-related data (element state, running identifier, configuration information) and methods (initialization, start, pause, reset, etc.), accepts calls from the user layer, and links with the core module layer; The core module layer comprises six modules: configuration management, lifecycle management, state management, animation execution, callback management, and resource cleanup. These modules are responsible for parameter processing, lifecycle binding, state tracking, animation execution, callback triggering, and resource recycling, respectively. Presentation layer: By combining WXML templates with data binding, animation effects are dynamically rendered based on the element's state, controlling the element's display status.

[0030] II. Specific Implementation Steps (a) Step S1: Create animation behavior module Build a general animation behavior module that encapsulates core animation logic applicable across different scenarios, clearly defines four types of core interfaces and methods, and integrates preset configuration templates and resource management mechanisms: Parameter interface: Used to receive user-defined configurations, with reserved parameter fields covering 12 core parameter categories (such as...). Figure 6 As shown, it includes basic parameters such as the number of target elements (elementCount), element display interval (interval), and animation auto-start flag (autoStart), as well as extended parameters such as animation delay execution time (startDelay), number of loops (loop), animation execution direction, debug mode switch (debug), easing function type, data field name for storing element state (dataKey), base CSS class name (cssClass), and visible CSS class name (visibleClass); Animation control methods: four core operation methods are preset: start (startFadeInAnimation), pause (pauseFadeIn), reset (resetFadeIn), and resume, covering the control needs of the entire animation lifecycle; Lifecycle hooks: Bind to the attached (initialize resources), ready (initialize animation configuration), detached (clean up resources) lifecycles of mini-program components to ensure that animation resources are synchronized with the page / component lifecycle; Status query interface: Provides the getFadeInState method as a unified entry point for obtaining status, and supports real-time return of animation running status, progress and other information; Pre-configured templates: Pre-configured templates suitable for typical scenarios such as product fade-in, countdown scrolling, and pop-up entry. Each template contains default parameters adapted to the scenario. Resource cleanup logic: Integrate timer recycling, data reference release, and other logic within the module to avoid memory leaks.

[0031] (ii) Step S2: Introduce the animation behavior module In the target page or component where animation effects are required, the animation behavior module (fadeInBehavior) created in step S1 is included in the page / component's dependency list (e.g., using the Mini Program's Behavior import mechanism). Figure 5 As shown, `Page({behaviors:[fadeInBehavior]})`. After importing, the target page / component automatically inherits all the module's data (such as the element state array `elementsVisible`, the configuration object `fadeInConfig`, and the running status flag `fadeInRunning`), control methods (start, pause, etc.), and lifecycle hook functions. There is no need to repeatedly write basic animation logic, enabling cross-page / component reuse of animation logic.

[0032] (III) Step S3: Configuration Object Merging and Verification Receive user configurations, merge and verify them, and generate the final runtime configuration. Specific process: Receiving user configuration: Users pass in a configuration object (userConfig) through the module's initFadeIn method. There are two configuration methods: one is to directly pass in the complete set of parameters, and the other is to specify a preset configuration template name and selectively override some parameters. The parameters in the configuration object can support static values, dynamic functions, or reactive data. For example, the display interval can be dynamically calculated based on the element index using the dynamic function interval=100*(index+1) to accelerate the sequence animation. Parameter validation: Prioritize checking the validity of key parameters, with a focus on verifying whether elementCount is a positive integer. If valid, continue with the subsequent process; otherwise, automatically replace it with the default value of 7. At the same time, validate other parameters, such as time-related parameters (interval, startDelay) which must be non-negative values, and loop counts which must be non-negative integers, to ensure that the parameters are valid. Define default configuration: A built-in default configuration object (defaultConfig) has default values ​​for its parameters, such as... Figure 6 As shown, the default values ​​are: elementCount (7), interval (500 milliseconds), startDelay (0 milliseconds), dataKey ("elementsVisible"), cssClass ("fade-in"), visibleClass ("visible"), and autoStart (false). Parameter merging: The module deeply merges the user configuration with the built-in default configuration to generate the final runtime configuration (finalConfig={...defaultConfig,...userConfig}), with user configuration parameters having higher priority than the default configuration; Initialize element state: Check if the field corresponding to dataKey in the page / component data already exists and has the same length as elementCount: If it exists and the length is correct, retain the existing state; if it does not exist or the length is incorrect, create a boolean array with length elementCount and initial value of false (elements=newArray(elementCount).fill(false)) to track the display state of each element; Save configuration and debug output: The final configuration (fadeInConfig:finalConfig), the element status array ([dataKey]:elements), and the running status flag (fadeInRunning:false) are saved using the setData method; if the debug parameter is true, "FadeInBehavior initialization complete, finalConfig" and the specific configuration information will be output to the console; Automatic startup check: If the `autoStart` parameter is true, then after initialization, the `startFadeInAnimation` method is triggered after a delay of `startDelay` milliseconds via `setTimeout` to automatically start the animation; if it is false, it waits for an external call to start (e.g., ...). Figure 6 (As shown).

[0033] (iv) Step S4: Timer sequence management and batch animation execution Based on the final runtime configuration, the module automatically manages the timer sequence within its own lifecycle to achieve sequential or parallel animation effects for multiple elements. The specific process is as follows (e.g.) Figure 1 (as shown) Initialize the state array: Based on elementCount in the final configuration, confirm that the element state array (elementsVisible) has been initialized. The array index corresponds one-to-one with the target element, and the initial value is false (indicating that the element is not displayed). Creating a timer sequence: First, execute the `_cleanupFadeInTimers` method to clean up old timers and avoid repeated execution; then, create timer tasks based on `elementCount` in a loop, with the loop range `i` from 0 to `elementCount-1`, and the timer delay time for each element is `i*interval+startDelay` (for sequential animation). If it is a parallel animation, the delay time is uniformly set to `startDelay`; create the corresponding timer tasks based on the calculation results to form an ordered timer sequence. Execute the timer task: After the timer is triggered, first check if the fadeInRunning state is true (to ensure that the animation is not paused). If it is true, get the current element state array (currentElements=this.data[dataKey]), set currentElements[i] to true, update the element state through the setData method, trigger the update of the mini program view layer, and make the target element present the preset animation effect (such as fade in, slide down); if the debug parameter is true, output "Display element i" (i is the index of the current element) to the console. Callback trigger judgment: After the element state is updated, check if the onElementShow callback function exists. If it exists, call onElementShow.call(this,i) with the element index as the parameter. At the same time, check if i is equal to elementCount-1. If it is true, trigger the onComplete callback function to indicate that all element animations have been completed. Command response processing: If a pause or reset command is received during animation execution, all unexecuted timer tasks are immediately cleared; when paused, the current state array and elapsed time are retained; when reset, the state array is restored to its initial value, and the animation state flag is updated.

[0034] (V) Step S5: Animation control method response and execution Throughout the animation's lifecycle, the module responds to external calls (such as a user clicking a button) or internal lifecycle triggers (such as page loading completion) by executing the corresponding animation control methods. The core process is as follows: Figure 4 As shown: Startup operation: Supports three startup methods (such as...) Figure 4 As shown): Method 1 is automatic startup (autoStart:true), triggered after the page / component's ready lifecycle or initialization delay startDelay; Method 2 is manual startup, directly calling the startFadeInAnimation method; Method 3 is external triggering, calling the startup method through other events (such as the button click event startPageAnimation); when starting, old timers are cleared first, then a new timer sequence is created, fadeInRunning is updated to true, and the animation status is set to "running"; It should be noted that: The complete execution logic of startFadeInAnimation is the core control logic of the entire animation "start-execution-callback" process. The specific steps are as follows: I. Process Trigger: User calls the startup method The entry point of the process is when the user calls the startFadeInAnimation method (such as when a button on the page is clicked or when it is automatically started). After the trigger is initiated, the process proceeds to the subsequent verification and execution stages.

[0035] II. Pre-verification: Initialization and runtime status check This stage is used to prevent animations from starting repeatedly or executing before initialization, ensuring the legitimacy of the process: Check if fadeInConfig exists Logic: Determine if the animation configuration object (finalConfig generated during the initialization phase) already exists; If it does not exist: return "Uninitialized" directly, and the process ends; If it exists: Proceed to the next verification step.

[0036] Check fadeInRunning status Logic: Determine if the animation's current running status flag (fadeInRunning) is true; If true: Return "Already running" and the process ends; If not (false): Proceed to the animation startup preparation stage.

[0037] III. Startup Preparation: Status Setup and Resource Cleanup After completing the pre-verification, proceed with the animation startup initialization process: Set running status Action: Set the fadeInRunning state to true to indicate that the animation has entered the "running" state.

[0038] Debug log output Logic: Determine if the debug parameter in the configuration is true; If so: Print a "Start Animation" log to the console for easier debugging; If not: Skip log output.

[0039] Clean up old timers Operation: Call the _cleanupFadeInTimers method to clear any remaining timers (to avoid animation chaos caused by repeated execution).

[0040] IV. Core Execution: Timer Sequence Creation and Element Animation Triggering This is the core step in animation execution, which uses a loop to create timers to animate multiple elements in sequence: Create a timer sequence Logic: Based on elementCount (total number of elements) in the configuration, loop through index i (from 0 to elementCount-1). Operation: Calculate the timer delay time for each element (delay=i*interval, where interval is the element display interval) and create the corresponding setTimeout timer task.

[0041] Save timer reference Operation: Store each created timer instance into the _fadeInTimers array (for cleanup during subsequent pause / reset).

[0042] V. Timer Triggering: Element State Updates and Callbacks When the timer of an element reaches its delay time, the following sub-process is triggered: Check the fadeInRunning status (secondary verification). Logic: Check again whether fadeInRunning is true (to prevent the animation from being paused when the timer is triggered); If not (false): Skip subsequent operations; If true: Enter the element state update phase.

[0043] Update element display status Operation 1: Get the current element state array (currentElements=this.data[dataKey], where dataKey corresponds to the field name of the state array); Operation 2: Set the state of the current element at index i to true (currentElements[i]=true); Operation 3: Call the mini program's setData method to synchronize the updated state array to the view layer and trigger the element's animation effect (such as fade-in display).

[0044] Debug log output (optional) Logic: Check again whether the debug parameter is true; If so: Print "Display element i" to the console (i is the index of the current element); If not: Skip log output.

[0045] VI. Callback Trigger: Linking the logic of a single element with the logic of all elements being completed. After the element's state is updated, the corresponding callback function is triggered, enabling the animation to be linked with the business logic: Trigger the onElementShow callback (for a single element). Logic: Determine if the onElementShow callback function is defined in the configuration; If it exists: call onElementShow.call(this,i), passing the current element index i as a parameter to the user-defined logic; If not present: skip this step.

[0046] Determine if it is the last element Logic: Determine if the current element index i is equal to elementCount-1 (i.e., whether it is the last element); If so: Call the _onAnimationComplete method to trigger subsequent logic for "all elements completed" (such as the onComplete callback). If not: Skip this step.

[0047] 7. Loop Check: Does the animation repeat? After completing the process for a single element, determine whether loop playback is needed: Check loop configuration Logic: Determine whether the animation loop is enabled (using the loop parameter in the configuration); If so: Return to the "Create Timer Sequence" step, regenerate the timer, and implement the looping animation; If not: The process ends.

[0048] 8. Process Closure: Return Results In the following scenarios, the process will terminate directly and return the corresponding result: Uninitialized (fadeInConfig does not exist): Returns "Uninitialized"; Already running (fadeInRunning is true): Returns "Already running"; If a single element completes its process without looping, simply return, and the process ends.

[0049] Pause operation: When the pauseFadeIn method is executed, in addition to clearing unexecuted timers, the complete animation state is serialized and saved, including the list of elements that have been displayed (elementsVisible), the current progress value (progress), the time consumed, and the current configuration parameters (finalConfig). Reset operation: When the resetFadeIn method is executed, all timers are cleared, the element state array is restored to all false, the progress value is set to 0, fadeInRunning is set to false, the onReset callback function is triggered, and the animation state is updated to "reset"; Resume Operation: When executing the resume command, calculate the trigger time point of the remaining animation sequence (time consumed + index of remaining element * interval) based on the complete state saved when paused, recreate the timer task, and continue the animation from the paused node to ensure smooth animation transitions; Resource cleanup: When a page / component triggers its detached lifecycle (such as when the user closes the page), the _cleanupFadeInTimers method is automatically called to clear all unreclaimed timer resources, release animation-related data references, and avoid memory leaks.

[0050] (vi) Step S6: Callback function triggering and expansion At key points in the animation execution, the module automatically triggers three preset types of callback functions (such as...). Figure 3 As shown), it supports user-defined logic extensions: The first type of callback function (onElementShow): is triggered when a single element completes its display animation. The index value of the element is passed as a parameter. Users can implement personalized logic based on this callback, such as adding labels to elements with specific indices or triggering associated animations. The second type of callback function (onComplete) is triggered when the animation sequence of all elements has been completed (when i===elementCount-1). No parameters are passed. Users can use this callback to perform subsequent operations, such as displaying a "loading complete" prompt or unlocking page interactive functions. The third type of callback function (onReset): is triggered when the animation is reset to its initial state. No parameters are passed. Users can use this callback to clear the page state, hide related prompts, etc.

[0051] (vii) Step S7: Real-time query and return of animation status Users can obtain the animation's running status information in real time through the module's getFadeInState interface. The interface returns a standardized status object containing three core fields: status: a string type, with values ​​of "not started", "running", "paused", "completed" or "reset", clearly indicating the current stage of the animation; currentIndex: An integer representing the index of the most recently displayed element. If the display has not started or has been reset, it is -1. progress: A floating-point type with a value range of 0-1. It is calculated by "number of elements already displayed / total number of target elements" and accurately reflects the overall progress of the animation.

[0052] (viii) Additional steps: Animation fault tolerance and adaptive adjustment During animation execution, the module monitors the running status of the mini-program page in real time to ensure animation stability and page smoothness. Performance Adaptive: Continuously monitors page frame rate and system resource usage. When the frame rate is detected to be lower than the preset threshold (e.g., 50 frames / second), it is determined to be a performance bottleneck. It automatically extends the element display interval or skips non-critical transition frames, reduces the animation execution frequency, and prioritizes ensuring smooth page operation. Anomaly degradation handling: When the target element is detected to be missing (e.g., not rendered due to network latency) or the configuration parameters are invalid (e.g., dynamic function execution error), a predefined degradation scheme is executed, including skipping the abnormal element and continuing to execute subsequent animations, using basic styles to replace animation effects, etc., to avoid program errors affecting the overall functionality.

[0053] The detailed workflow of this patent revolves around the core logic of "modular encapsulation - flexible integration - dynamic configuration - full lifecycle control - state traceability - fault tolerance and adaptation," covering the entire chain from system design, development, application to maintenance. Ultimately, it achieves cross-scene reuse of animation logic, flexible configuration expansion, and stable and controllable operation. The specific process is divided into seven stages: Phase 1: System Architecture Design and Core Objective Determination This phase aims to clarify the overall system architecture and technical goals, provide a framework for subsequent development, and solve the core problems of traditional animation systems, such as difficulty in reuse, rigid configuration, and chaotic management.

[0054] Core Objectives Defined: Three core objectives are set: cross-page / component reuse of animation logic, flexible configuration of more than 12 types of parameters, and controllable animation lifecycle (start / pause / reset / resume), while taking into account both lightweight design and performance stability.

[0055] Four-layer architecture design: Design a four-layer architecture consisting of "User Layer - Behavior Layer - Core Module Layer - Presentation Layer", clearly defining the responsibilities of each layer and the data flow relationship: Usage layer: The target page / component acts as the caller of the animation function and does not need to concern itself with the underlying logic; Behavior layer: The core bridge, encapsulating animation data, methods, and lifecycle hooks to enable logic reuse; Core module layer: It includes six sub-modules such as configuration management, lifecycle, state management, and animation execution, and is responsible for the execution of core logic; Presentation layer: Dynamically renders animation effects by binding data with WXML templates.

[0056] Technology stack adaptation: Based on the WeChat Mini Program development framework, it adapts to its Behavior mechanism, page / component lifecycle and data binding syntax to ensure system compatibility.

[0057] Phase 2: Core Module Development Process This stage is the core of system implementation. It encapsulates general animation logic through modular development and builds reusable and scalable core functional modules.

[0058] (I) Sub-phase 2.1: Behavior animation module development Interface and method definition: Encapsulates four core interfaces and control methods, including a parameter interface that receives 12 types of parameters, animation start / pause / reset / resume control methods, mini-program lifecycle hook functions, and a state query interface (getFadeInState).

[0059] Preset configuration template development: Preset configuration templates are developed for typical scenarios such as product fade-in, countdown scrolling, and pop-up entry. Each template contains default parameters adapted to the scenario (such as the default loop=1 and startDelay=300ms for the pop-up entry template).

[0060] Resource management logic development: Integrate timer recycling and data reference release logic, and implement the _cleanupFadeInTimers method inside the module to avoid memory leaks.

[0061] (II) Sub-phase 2.2: Development of core functional sub-modules Configuration Management Submodule: Develops functions for parameter validation, default configuration merging, and dynamic parameter parsing, supporting configuration methods for static parameters, dynamic functions, and reactive data.

[0062] The timer sequence management submodule develops logic for timer creation, serialization storage, and sequential triggering, supports calculating delay time by element index, and enables sequential animation of multiple elements.

[0063] Callback function submodule: Develop the triggering logic for three types of callback functions: onElementShow (single element completion), onComplete (all elements completed), and onReset (reset), to decouple animation from business logic.

[0064] The status management submodule develops functions for tracking animation status (not started / running / paused / completed / reset), calculating progress (progress = number of completed elements / total number of elements), and supports real-time status queries.

[0065] Fault Tolerance and Adaptive Submodule: Develop performance adaptive (monitor frame rate and dynamically adjust animation frequency) and exception degradation (skip exceptions when elements do not exist / parameters are invalid) functions to improve system robustness.

[0066] Phase 3: Integrated Application Process This phase is geared towards users (developers), providing a simple and easy-to-use integration method to enable rapid access to animation functions.

[0067] Module import steps: Developers import the animation module in the target page / component using Page({behaviors:[fadeInBehavior]}), which automatically inherits all the module's data, methods, and lifecycle hooks.

[0068] Configuration initialization steps: Developers pass in the configuration via the initFadeIn method, supporting two configuration methods: Pass the complete set of parameters directly (e.g., {elementCount:10,interval:300}). Specify a preset template name and override some parameters (e.g., {template:'productFade',interval:400}).

[0069] View layer binding steps: In WXML, associate the element's display state through data binding (such as [elementsVisible[index]?'visible':'']) and bind CSS animation styles (such as fade-in transition effects).

[0070] Phase 4: Operation Control Process This stage covers the entire lifecycle of the animation from start to finish, enabling fine-grained control and state linkage.

[0071] (a) Animation startup process (corresponding to the startFadeInAnimation method) Pre-verification: Check if fadeInConfig exists (return if not initialized) and if fadeInRunning is true (return if already running).

[0072] Startup preparation: Set fadeInRunning:true. If debug mode is enabled, output logs and call _cleanupFadeInTimers to clean up old timers.

[0073] Timer creation: Create timers based on the elementCount loop, calculate the delay time for each element (delay=i*interval+startDelay), and store the timer instance in the _fadeInTimers array.

[0074] Animation trigger: After the timer expires, the fadeInRunning state is checked again, the element display state is updated (currentElements[i]=true), and the animation is triggered in the view layer.

[0075] (II) Animation Intermediate Control Flow Pause process: Call the pauseFadeIn method to clear unexecuted timers and serialize and save the current state (list of completed elements, progress, configuration parameters).

[0076] Recovery process: Based on the state saved during pause, calculate the delay time of the remaining elements, recreate the timer, and continue execution from the paused node.

[0077] Reset process: Call the resetFadeIn method to clear all timers, restore the element state array to all false, set fadeInRunning: false, and trigger the onReset callback.

[0078] (III) Animation End Process Single element completion: Triggers the onElementShow callback, passing the current element index, allowing developers to extend personalized logic.

[0079] All elements complete: When the last element (i=elementCount-1) is completed, if loop is enabled, the animation will restart; otherwise, the onComplete callback will be triggered to execute subsequent business logic.

[0080] Phase 5: Status Management and Monitoring Process This stage enables real-time tracking and querying of animation status, supporting debugging and business logic integration.

[0081] Real-time status updates: During the animation process, the three core status data types, status (status identifier), currentIndex (index of the most recently completed element), and progress (progress), are updated in real time.

[0082] Status query interface call: Developers can obtain standardized status objects at any time through the getFadeInState interface for debugging or page interaction logic (such as displaying a loading bar based on progress).

[0083] Debug log output: When debug:true, console logs are output at key nodes (initialization complete, animation start, element display), including configuration information, element index and other details, to facilitate troubleshooting.

[0084] Phase 6: Resource Cleanup and Lifecycle Synchronization Process This phase ensures that animation resources are synchronized with the page / component lifecycle to avoid memory leaks and resource waste.

[0085] Component lifecycle linkage: Bind attached (initialize resources), ready (initialize configuration), and detached (clean up resources) hook functions in the Behavior module.

[0086] Page close cleanup: When a page / component triggers its detached lifecycle, the _cleanupFadeInTimers method is automatically called to clear all timers and release data references.

[0087] Manual cleanup support: Provides an interface for manually calling resource cleanup methods, allowing developers to proactively reclaim resources based on business scenarios.

[0088] VII. Phase 7: Process Closure and Reusable Extended Process This phase enables the system to be reused and extended, supporting the reuse of animation logic across scenes and pages.

[0089] Cross-page / component reuse: The same animation module can be imported by multiple pages / components, and each importer independently maintains its own configuration and state without interfering with each other.

[0090] Scene expansion: Adapt to new animation scenes (such as list scrolling loading, button click feedback) by adding new preset templates or custom parameters.

[0091] Feature Expansion: Supports adding new features (such as adding animation speed adjustment and custom easing function libraries) by extending the sub-modules of the core module layer.

[0092] VIII. Core Process Advantages and Technical Effects Improved reusability: Through Behavior encapsulation, animation logic can be reused across pages / components, reducing code redundancy by more than 90%.

[0093] Configuration flexibility: Supports three configuration methods: 12 types of parameters, preset templates + custom overriding, and dynamic parameters, adapting to diverse scenarios.

[0094] Enhanced controllability: Covers the entire lifecycle control of animations (start / pause / reset / resume), supports real-time status query, and meets complex interaction needs.

[0095] Stability assurance: Through parameter verification, fault tolerance degradation, and automatic resource cleanup, we ensure stable operation under different devices and abnormal scenarios.

[0096] III. Implementation Results Description Through the above implementation steps, the present invention achieves the following technical effects: Animation logic reuse: By encapsulating the animation logic through the Behavior module, the animation logic can be reused across pages / components, reducing code redundancy by more than 90%; Configuration flexibility: Supports 12 types of configurable parameters, combined with preset templates and dynamic parameters, to adapt to diverse business scenarios; Controllable lifecycle: By using control methods such as start, pause, reset, and resume, combined with lifecycle hooks and automatic resource cleanup, memory leaks are avoided; Status traceability: Real-time query of animation status and progress is achieved through standardized status objects, supporting debugging and interactive logic expansion; Robustness Enhancement: Through parameter verification, fault tolerance monitoring, and degradation solutions, we ensure that the animation runs stably under different devices and abnormal scenarios.

[0097] This implementation method does not rely on third-party animation libraries, thus maintaining the lightweight nature of mini-programs. At the same time, it solves the problems of rigid configuration, limited functionality, and poor scalability in existing technologies. It is suitable for various mini-program animation scenarios such as onboarding animations, product list loading, countdown scrolling, and pop-up entry.

[0098] The above embodiments are merely preferred embodiments of the present invention and should not be construed as limiting the scope of protection of the present invention. Any non-substantial changes and substitutions made by those skilled in the art based on the present invention shall fall within the scope of protection claimed by the present invention.

Claims

1. A reusable animation control method based on behavior patterns, characterized in that, The method includes the following steps: Step S1: Create an animation behavior module that encapsulates common animation logic and defines parameter interfaces for configuring animation effects, animation control methods, lifecycle hook functions, and status query interfaces. Step S2: Import the animation behavior module into the target page or component, so that it inherits the data, methods and lifecycle of the module; Step S3: Receive the configuration object provided by the user through the parameter interface. The configuration object includes at least one or more parameters such as the number of target elements, element display interval time, and animation auto-start flag. Merge and verify the user configuration with the default configuration defined in the module to generate the final running configuration. Step S4: According to the final running configuration, during the lifecycle of the animation behavior module, a timer sequence is automatically managed through the animation execution logic encapsulated within it, so as to control the display status of multiple target elements in a sequential or parallel manner, thereby achieving batch animation effects; Step S5: During animation execution, in response to external calls or internal lifecycle triggers, the animation control method is executed, and the control method includes at least start, pause, and reset; Step S6: Trigger preset callback functions at different stages of animation execution. The callback functions include at least the callback when a single element is displayed and the callback when the entire animation is completed. Step S7: Obtain and return the current running status of the animation, the number of elements that have completed the animation, and the total progress information in real time through the status query interface.

2. The reusable animation control method based on behavior patterns according to claim 1, characterized in that, The configuration object in step S3 also includes at least one of the following parameters: animation delay execution time, whether to loop the animation, number of loops, animation execution direction, whether to enable debug mode, animation easing function type, data field name for storing element state, base CSS class name, and display state CSS class name.

3. The reusable animation control method based on behavior patterns according to claim 1, characterized in that, Step S4, "automatically managing a timer sequence through its internally encapsulated animation execution logic to control the display state of multiple target elements in a sequential or parallel manner," specifically includes: Step S4.1: Based on the number of target elements in the final running configuration, initialize a state array to track the display status of each element; Step S4.2: Based on the element display interval time, calculate the timed trigger time point corresponding to each element, and create a corresponding timer task to form a timer sequence; Step S4.3: Execute the timer tasks sequentially according to the timer sequence. When each task is executed, update the display state of the corresponding element in the state array and trigger the view layer update of the mini-program framework. Step S4.4: If a pause or reset command is received during animation execution, immediately clear all timer tasks that have not yet been executed, and update the animation status according to the command.

4. The reusable animation control method based on behavior patterns according to claim 1, characterized in that, The "triggering the preset callback function" in step S6 specifically includes: When a single element is finished displaying, the first type of callback function is triggered, and the index of the currently displayed element is passed as a parameter to the function; The second type of callback function is triggered when all element animation sequences have finished executing; The third type of callback function is triggered when the animation is reset to its initial state.

5. The reusable animation control method based on behavior patterns according to claim 1, characterized in that, The step S7, "real-time acquisition and return of the current running status of the animation, the number of elements that have completed the animation, and the total progress information," specifically includes: Returns a state object containing the following fields: status: A string indicating the current status of the animation, with values ​​including "not started", "running", "paused", "completed" or "reset"; currentIndex: An integer value representing the index of the most recently displayed element; progress: A floating-point value representing the overall progress of the animation, calculated by dividing the number of elements currently displayed by the total number of elements.

6. The reusable animation control method based on behavior patterns according to claim 1, characterized in that, The animation behavior module is pre-configured with preset configuration templates suitable for different scenarios; in step S3, the user generates the configuration object by specifying the name of the preset configuration template and selectively overriding some of its parameters.

7. The reusable animation control method based on behavior patterns according to claim 1, characterized in that, At least one parameter in the configuration object is a dynamic function or reactive data. The dynamic function can dynamically calculate parameter values ​​based on element index, animation progress, or external data to achieve non-linear sequence animation effects.

8. The reusable animation control method based on behavior patterns according to claim 1, characterized in that, The method also includes animation fault tolerance and adaptive steps: Real-time monitoring of the frame rate or system resource usage of the mini-program page; When a performance bottleneck is detected, the animation execution frequency is automatically reduced or non-key frames are skipped to ensure page smoothness. When the target element is detected to be non-existent or the configuration parameters are invalid, a predefined degradation scheme is executed to avoid program errors.

9. A reusable animation control method based on behavior patterns according to claim 1, characterized in that, The "pause" operation in the animation control method specifically includes: Clear currently unexecuted timer tasks; The complete state of the animation is serialized and saved, including the list of elements that have been displayed, the current progress, the time consumed, and the current configuration parameters. The animation control method also includes a "restore" operation, which calculates the remaining animation sequence based on the saved complete state and resumes the animation from the paused node.