clearInterval()不起作用 [英] clearInterval() not working

查看:114
本文介绍了clearInterval()不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

JS - 如何在使用setInterval()后清除间隔

我有一个函数,使用 setInterval font-family >(我只是练习JavaScript。)通过单击on按钮调用该函数,并且应该使用单独的按钮off清除间隔。但是,关闭按钮实际上并没有清除间隔,它只是继续。我怀疑这与范围有关,但我不知道如何以其他方式编写它。另外,我不想用jQuery这样做,因为毕竟我正在学习它。

I have a function that changes the font-family of some text every 500 ms using setInterval (I made it just to practice JavaScript.) The function is called by clicking on an "on" button and the interval is supposed to be cleared using a separate button, "off". However, the "off" button doesn't actually clear the interval, it just continues. I suspect that this has something to do with scope but I'm not sure how to write it any other way. Also, I don't want to do this with jQuery because, after all, I'm doing it to learn.

<body>
<p><span id="go" class="georgia">go</span> Italian</p>
<p>
    <button id="on" type="button" value="turn on">turn on</button>
    <button id="off" type="button" value="turn off">turn off</button>
</p>

<script>
var text = document.getElementById("go");
var on = document.getElementById("on");
var off = document.getElementById("off");

var fontChange = function() {
    switch(text.className) {
        case "georgia":
            text.className = "arial";
            break;
        case "arial":
            text.className = "courierNew";
            break;
        case "courierNew":
            text.className = "georgia";
            break;      
    }
};

on.onclick = function() {
    setInterval(fontChange, 500);
};

off.onclick = function() {
    clearInterval(fontChange);
}; 
</script>
</body>


推荐答案

setInterval 返回一个ID,然后用它来清除间隔。

setInterval returns an ID which you then use to clear the interval.

var intervalId;
on.onclick = function() {
    if (intervalId) {
        clearInterval(intervalId);
    }
    intervalId = setInterval(fontChange, 500);
};

off.onclick = function() {
    clearInterval(intervalId);
}; 

这篇关于clearInterval()不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆