如何让音频录制脚本中指定jQuery操作仅执行一次?
Got it, let's work through this problem step by step. The goal is to trigger that specific jQuery progress bar action only once each time the sound level goes above -1, while still properly resetting the bar when the level drops back to -1.
Core Approach
We'll use a simple flag variable to track whether we've already run the progress bar animation for the current "active" sound level session. When the level returns to -1, we reset this flag so the action can fire again if the level goes up later.
Full Code Implementation
// Flag to track if we've executed the progress bar action for the current active level let hasTriggeredProgress = false; function callback_activityLevel(level) { const levelBar = $(".progress-bar-fill"); if (level === -1) { // Reset level bar width to 0px as required levelBar.css('width', '0px'); // Reset the flag so we can trigger the action again if level rises later hasTriggeredProgress = false; } else { // Only run the jQuery delay+width change if we haven't done it yet for this session if (!hasTriggeredProgress) { levelBar.delay(1000).queue(function () { $(this).css('width', '100%'); // Mark the action as executed to prevent repeats hasTriggeredProgress = true; // Don't forget to dequeue to unblock future queue actions on this element $(this).dequeue(); }); } // Insert your existing levelbar width cycling logic here for when level > -1 // ... } }
Key Notes
- Flag Management: The
hasTriggeredProgressvariable ensures the delay-and-expand action only runs once per active level period. Resetting it when level hits -1 lets the action trigger again if the sound becomes active later. - Dequeue Call: Adding
$(this).dequeue()inside the queue function is critical—jQuery's animation queue will stop processing unless you explicitly dequeue the next item, which avoids blocking future animations on the progress bar. - Scope: Keep the flag variable in a scope that persists between calls to
callback_activityLevel(don't define it inside the function itself, or it'll reset every time). If you're working in a component/module, wrap this in a closure to avoid polluting the global scope.
Edge Case Handling
If you ever need to manually re-trigger the progress bar action (without waiting for the level to drop to -1), just set hasTriggeredProgress = false wherever you need that reset.
内容的提问来源于stack exchange,提问作者rtaskiran0

