You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何清除之前的setInterval?附jQuery代码优化需求

Fixing Lingering Intervals & Optimizing Your jQuery Code

Hey there! Let's tackle that stubborn interval problem first—then we'll clean up the code to make it simpler to maintain and tweak later.

The Root of the Interval Issue

Right now, your loop and instIntervall variables are declared inside each if/else branch. That means every time you switch the select option, new variables get created, and you lose access to the old interval IDs. So those old timers just keep running in the background, even after you've switched to a new mode!

The Fix & Optimized Code

We'll make two key changes:

  1. Move interval variables outside the event handler so we can access and clear them every time the select changes
  2. Extract repeated logic into helper functions to cut down on duplicate code (no more copying the same 10 lines three times!)

Here's the revised code:

// Declare interval variables outside the handler to keep track of them across changes
let soundLoopInterval = null;
let textUpdateInterval = null;

$('#hometrainerSelectIntervall').on('change', function() { 
    // First, clear any existing intervals to stop old timers immediately
    if (soundLoopInterval) clearInterval(soundLoopInterval);
    if (textUpdateInterval) clearInterval(textUpdateInterval);

    // Helper function to handle interval text switching (avoids repeated code)
    function setupIntervalText(elementId, textOptions) {
        let counter = 0;
        const targetElement = document.getElementById(elementId);
        
        function updateText() {
            targetElement.innerHTML = textOptions[counter];
            counter = (counter + 1) % textOptions.length; // Clean way to reset counter to 0
        }

        // Update text right away instead of waiting for the first interval tick
        updateText();
        // Return the interval ID so we can clear it later
        return setInterval(updateText, time);
    }

    const selectedMode = this.value;
    const time = parseInt($(this).find(":selected").data("time")) * 60 * 1000;

    // Hide all interval boxes first (no need to repeat this in every branch)
    $(".hometrainerIntervallWarmingUp, .hometrainerIntervallMuscleAndRestday, .hometrainerIntervallBoxing").hide(100);

    if (selectedMode === 'timeWarmingUp') { 
        $(".hometrainerIntervallWarmingUp").delay(150).show(100);
        soundLoopInterval = setInterval(() => $.playSound("/BETA/includes/boxing/sounds/BELL_HOMETRAINER.mp3"), time);
        textUpdateInterval = setupIntervalText("intervallWarmingUp", [
            "<i class='fas fa-chevron-circle-up'></i> STUFE 2 <i class='fas fa-chevron-circle-up'></i> ", 
            "<i class='fas fa-chevron-circle-down'></i> STUFE 1 <i class='fas fa-chevron-circle-down'></i>"
        ]);
    } else if (selectedMode === 'timeMuscleAndRestday') { 
        $(".hometrainerIntervallMuscleAndRestday").delay(150).show(100);
        soundLoopInterval = setInterval(() => $.playSound("/BETA/includes/boxing/sounds/BELL_HOMETRAINER.mp3"), time);
        textUpdateInterval = setupIntervalText("intervallMuscleAndRestday", [
            "<i class='fas fa-chevron-circle-up'></i> STUFE 3 <i class='fas fa-chevron-circle-up'></i> ", 
            "<i class='fas fa-chevron-circle-down'></i> STUFE 2 <i class='fas fa-chevron-circle-down'></i>"
        ]);
    } else if (selectedMode === 'timeBoxing') { 
        $(".hometrainerIntervallBoxing").delay(150).show(100);
        soundLoopInterval = setInterval(() => $.playSound("/BETA/includes/boxing/sounds/BELL_HOMETRAINER.mp3"), time);
        textUpdateInterval = setupIntervalText("intervallBoxing", [
            "<i class='fas fa-chevron-circle-up'></i> STUFE 2 <i class='fas fa-chevron-circle-up'></i> ", 
            "<i class='fas fa-chevron-circle-down'></i> STUFE 1 <i class='fas fa-chevron-circle-down'></i>"
        ]);
    }
    // No need for an else block—we already hid all boxes at the start!
});

Key Improvements Breakdown

  1. Interval Cleanup: By keeping soundLoopInterval and textUpdateInterval outside the event handler, we can clear old timers every time the user switches modes—no more ghost intervals running in the background.
  2. Helper Function: setupIntervalText handles all the text switching logic in one place, so if you ever need to tweak how the text updates, you only have to change code once.
  3. Responsive Text Update: The text changes immediately when you select a mode, instead of waiting for the first interval tick.
  4. Less Duplication: We hide all interval boxes once at the start, instead of repeating the same hide code in every branch.

This should fix the lingering interval problem and make your code much easier to maintain going forward!

内容的提问来源于stack exchange,提问作者OMEXLU

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:07:24