Javascript setinterval继续刷新/循环 [英] Javascript setinterval keeps on refresh/looping

查看:364
本文介绍了Javascript setinterval继续刷新/循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个javascript,我会每1分钟调用一次函数。我的代码如下:

Hi, I have a javascript in which I will call a function every 1 minutes. My codes as below:

var clearTimer = setInterval(function ()
{
    MyMethod;
}, 60000);



然后在做了一些事情之后,我将clearInterval如下:


Then after doing some stuff, I will clearInterval as below:

clearInterval(clearTimer);
clearTimer = 0;



但有一点很奇怪,html页面点击间隔计时器,它会在显示页面之前刷新多次,刷新率不断增加每次刷新。



我尝试过:



尝试使用清除间隔,但结果是一样的。


But one thing which is weird where the html page hit the interval timer, it will refresh multiple times before displaying the page and the refreshing rate keeps on increasing on each time it refresh.

What I have tried:

Tried to use clear interval but the result is same.

推荐答案

我找到了解决方案。

我必须将脚本更改为IF声明如下:

I have found the solution.
I have to change the script into having IF statement as below:
if (clearTimer == 0) {
    clearTimer = setInterval(function () {
        MyMethod;
    }, 60000);
}





将clearTimer变量移动为全局变量并将其置于IF语句中以检查是否它为0然后只调用setInterval函数。

之前为什么代码继续循环是由于没有条件检查,每次调用方法时,它都会添加递归循环并继续累加到无限数。因此,当多次调用setinterval时,页面将继续刷新。



Move the clearTimer variable to become global variable and make it inside the IF statement to check if it is 0 then only call the setInterval function.
Previously on why does the codes keep on looping was due to there is no condition checking and every time the method is being called, it will add a recursive looping and will keep on accumulate to infinite number. Therefore the page will keep on refreshing as the setinterval is being called multiple times.


这篇关于Javascript setinterval继续刷新/循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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