Javascript clearInterval 和 setInterval() 的行为不符合预期

Javascript clearInterval and setInterval() acting not as expected

本文关键字:不符合 clearInterval setInterval Javascript      更新时间:2023-09-26
var timer = 0
var startInterval = function( value ) {
    timer = setInterval( "checkNewPost();", value );
}
var stopInterval = function() {
    clearInterval( timer );
}
jQuery("#centerColumn a").click(function() {
    var a_id = jQuery(this).attr("id");
    var splitValue = a_id.split("-");
    var newValue = splitValue[1];
    if( newValue == "30" ) { 
        stopInterval;
        startInterval( 10000 );
    }
    else if( newValue == "1" ) {
        stopInterval;
        startInterval( 20000 );
    }
    else if( newValue == "5" ) {
        stopInterval;
        startInterval( 30000 );
    }
    else if( newValue == "pause" )
        stopInterval;
});

正如您在我的代码中看到的那样,逻辑非常简单,当 newvalue 等于 30 时,它将停止当前间隔并在 setInterval 上以 10000 秒的速度重新启动它。当 newValue 等于暂停时,它将停止所有 setInterval。

这里的问题是它无法正确运行,我不知道为什么?有人可以指导我吗?您的帮助将不胜感激!

谢谢! :)

你需要

调用 stopInterval 函数

stopInterval();

我认为没有括号就行不通

替换

 stopInterval; // fonction simply put on stack

 stopInterval(); // fonction call

您对stopInterval的调用缺少它们后面的括号,因此您当前实际上并未调用该方法。

尝试使用stopInterval();

其他人都是对的,你应该使用 stopInterval() .此外,这是一个更紧凑、IMO 更具可读性的代码版本:

$('#centerColumn a').click(function () {
    var id = this.id.split('-')[1];
    var value = {
        30: 10000,
        1: 20000,
        5: 30000
    };
    id ==== 'pause' && stopInterval();
    if (value[id]) {
        stopInterval();
        startInterval(value[id]);
    }
});