简体   繁体   English

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

[英]Javascript clearInterval and setInterval() acting not as expected

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;
});

As you can see in my code, the logic is pretty straight forward, when newvalue is equal to 30 it will stop the current interval and restart it with a 10000 seconds on the setInterval. 如您在我的代码中所见,逻辑很简单,当newvalue等于30时,它将停止当前间隔,并在setInterval上以10000秒重新启动它。 And when newValue is equal to pause, it will stop all the setInterval. 当newValue等于暂停时,它将停止所有setInterval。

The problem here is it does not act correctly, i'm not sure why? 这里的问题是它无法正常运行,我不确定为什么吗? Can someone guide me on this. 有人可以指导我吗? Your help would be greatly appreciated! 您的帮助将不胜感激!

Thanks! 谢谢! :) :)

you need to call the stopInterval function 您需要调用stopInterval函数

stopInterval();

I think it won't work without the parentheses 我认为没有括号就行不通

Replace 更换

 stopInterval; // fonction simply put on stack

with

 stopInterval(); // fonction call

Your calls to stopInterval are missing the parentheses after them so you're currently not actually calling that method. 您对stopInterval调用缺少括号后的括号,因此您当前实际上并未在调用该方法。

Try using stopInterval(); 尝试使用stopInterval();

Everybody else is right, you should use stopInterval() . 其他人都是对的,您应该使用stopInterval() Also here's a more compact and IMO more readable version of your code: 另外,这是代码的更紧凑和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]);
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM