Javascript:在settimeout之前调用cleartimeout可以吗? [英] Javascript: Is it ok to call cleartimeout before settimeout?

查看:404
本文介绍了Javascript:在settimeout之前调用cleartimeout可以吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个设置计时器的函数,并在计时器到期时自行调用。

I have a function that sets a timer, and calls itself back upon expiration of the timer.

我想知道的是清除功能顶部的计时器是不好的做法。

What I'd like to know is if it is bad practice to clear the timer at the top of the function.

原因是因为我会不时地异步调用该函数,如果我不先清除定时器,我将同时运行两个。

The reason for this is because I will be calling that function asynchronously from time to time, and if I don't clear the timer first, I'll have two running simultaneously.

我意识到我可以在我对函数进行另一次调用之前清除计时器,但是我想知道如果我只是在任何浏览器中都会出现问题将cleartimeout调用保留在包含计时器的函数内。

I realize that I can clear the timer right before I make the other call to the function, but I'm wondering if it will cause problems in any browser if I just keep the cleartimeout call inside the function which contains the timer.

另一个想法 - 我可以在进行cleartimeout调用之前测试timer变量,看看它是否是一个计时器?

One other thought - Can I test the timer variable before making the cleartimeout call, to see if it is a timer?

以下是一些示例代码:

function onAir(){

    // reset timer  
    clearTimeout(timer);

    $.getJSON("http://mywebsite.com?format=json&callback=?",function(data){
        if(data.result == '1'){
            do stuff here   
        }
        else{
            do other stuff here
        }   
    });

    // start timer
    timer = setTimeout("onAir()",60000);
} 

感谢您与我分享您的大脑!

Thanks for sharing your brain with me!

Kenny

推荐答案

是的,没关系。此外,您应该像这样调用setTimeout():

Yes, that's fine. Also, you should call "setTimeout()" like this:

  timer = setTimeout(onAir, 60000);

这篇关于Javascript:在settimeout之前调用cleartimeout可以吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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