jQuery进度条函数重复执行问题求助:如何让函数仅运行一次
Fixing Your Non-Stop jQuery Progress Bar (Run Once Only)
Hey there! Let's get that progress bar behaving correctly—running only once, whether triggered by scroll or click, and stopping properly. Let's break down what's going wrong first, then fix it step by step.
What's Causing the Issue?
- Your
setIntervalkeeps checking the scroll position every 1 second forever, even after the progress bar has started. This means every time you scroll past the target, it re-runsloadBar(). - There's no flag to track if
loadBar()has already executed, so even if you fix the timer, repeated triggers (like multiple clicks or scrolls) would restart the animation. loadBar.stopNow()isn't a valid method—jQuery animations need to be stopped on the actual elements, not the function itself.
The Fixed Code
Here's the revised code with all fixes applied:
// Flag to track if loadBar has already run let isLoadBarExecuted = false; function loadBar() { var delay = 500; $(".progress-bar").each(function(i) { // Stop any existing animations on the progress bar first to prevent overlaps $(this).stop(true, true); // Animate the width $(this).delay(delay * i).animate({ width: $(this).attr('aria-valuenow') + '%' }, delay); // Animate the counter text $(this).prop('Counter', 0).animate({ Counter: $(this).text() }, { duration: delay, easing: 'swing', step: function(now) { $(this).text(Math.ceil(now) + '%'); } }); }); } $(document).ready(function() { // Handle click event on #webLangages (run only once) $('#webLangages').on('click', function() { if (!isLoadBarExecuted) { loadBar(); isLoadBarExecuted = true; } }); }); // Handle scroll trigger (run only once, then stop checking) var target = $("#third").offset().top; var interval = setInterval(function() { if ($(window).scrollTop() > target && !isLoadBarExecuted) { loadBar(); isLoadBarExecuted = true; clearInterval(interval); // Stop checking scroll position forever } }, 1000);
Key Fixes Explained
- Execution Flag: The
isLoadBarExecutedvariable ensures the function runs exactly once, no matter how many times the trigger (scroll/click) fires. - Clear the Timer: Once the scroll condition is met,
clearInterval(interval)stops the timer from checking the scroll position ever again. - Stop Existing Animations:
$(this).stop(true, true)clears any ongoing animations on the progress bar before starting new ones—this prevents messy overlapping animations if a trigger fires accidentally before the first run finishes. - Click Event Guard: The click handler now checks the flag before running
loadBar(), so repeated clicks won't restart the animation.
That should resolve your issue—your progress bar will run once, either when you scroll to the target or click the button, and won't repeat or get stuck running indefinitely.
内容的提问来源于stack exchange,提问作者Kamel
相关产品推荐
相关产品推荐

