简单的 Javascript 或 jQuery clearInterval 问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5517438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 17:27:20  来源:igfitidea点击:

Simple Javascript or jQuery clearInterval problem

javascriptjquerytimersetintervalclearinterval

提问by Jakub Hampl

I have gone through most of the code here and tried several ways to get clearInterval to work and for some reason it is just not working, although it is a basic and simple problem.

我已经浏览了这里的大部分代码,并尝试了几种方法来让 clearInterval 工作,但由于某种原因,它无法正常工作,尽管这是一个基本且简单的问题。

Here is the code and I want to know WHY it isn't working, not just get the code done for me.

这是代码,我想知道为什么它不起作用,而不仅仅是为我完成代码。

var myTimer;

function startTimer() {
    myTimer = window.setInterval( function() {
        $('#randomImage').fadeTo('slow',0.0).addClass("changeBg_" + current);
        var current = Math.round(Math.random() * 4) + 1;
        $('#randomImage').fadeTo('slow',1.0).addClass("changeBg_" + current);
    }, 5000);
};

function stopTimer(){
    window.clearInterval(myTimer);
    $('#randomImage').fadeTo('slow',0.0);

}

Thanks In Advance from a Newbie...

在此先感谢一个新手...

回答by Jakub Hampl

Your code is fine, it works perfectly. It must be a problem with the code calling it. Check out this fiddle.

你的代码很好,它完美地工作。一定是调用它的代码有问题。看看这个小提琴

var myTimer;

function startTimer() {
    myTimer = window.setInterval( function() {
        $('#randomImage').fadeTo('slow',0.0).addClass("changeBg_" + current);
        var current = Math.round(Math.random() * 4) + 1;
        $('#randomImage').fadeTo('slow',1.0).addClass("changeBg_" + current);
    }, 5000);
};

function stopTimer(){
    window.clearInterval(myTimer);
    $('#randomImage').fadeTo('slow',0.0);

}

startTimer();
$('#randomImage').click(function() { stopTimer(); });