如何通过clear interval停止jQuery波纹效果的持续过度叠加
Hey there! Let's fix that runaway ripple effect right away. The key here is keeping track of the timer ID returned by setInterval()—that's what lets you shut it down cleanly with clearInterval().
Step 1: Store the Interval ID
First, declare a variable in a scope that's accessible wherever you want to stop the ripple generation. This variable will hold the unique ID that setInterval() gives us:
// Declare this in a scope that's reachable by both start and stop logic let rippleTimer;
Step 2: Start the Ripple Effect & Save the ID
When you initialize your ripples and start the automatic ripple drops, assign the result of setInterval() to your stored variable:
// Initialize the jQuery ripples plugin $(".wavy").ripples({ interactive: false, perturbance: 0.01 }); // Start auto-generating ripples and save the timer ID rippleTimer = setInterval(function() { // Example logic to create random ripples (adjust as needed) const $target = $(".wavy"); const randomX = Math.random() * $target.width(); const randomY = Math.random() * $target.height(); // Trigger a ripple drop $target.ripples("drop", randomX, randomY, 25, 0.01); }, 800); // Adjust the interval (milliseconds) to control ripple frequency
Step 3: Stop the Effect with clearInterval()
Whenever you want to halt the automatic ripples—whether it's on a button click, after a set time, or when a user action happens—pass the stored timer ID to clearInterval():
// Example 1: Stop when a button is clicked $("#stop-ripple-btn").on("click", function() { clearInterval(rippleTimer); // Optional: Completely reset the ripple effect if needed // $(".wavy").ripples("destroy"); }); // Example 2: Stop automatically after 15 seconds setTimeout(function() { clearInterval(rippleTimer); }, 15000);
Quick Notes
- Make sure
rippleTimerisn't trapped inside a local function scope—otherwise you won't be able to access it to stop the interval later. - If you want to fully reset the ripple effect (not just stop new ripples), use the plugin's
destroymethod as commented in the example.
内容的提问来源于stack exchange,提问作者webguy

