Javascript 如何使用函数设置和获取间隔

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13588866/
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-26 19:12:46  来源:igfitidea点击:

Javascript How to set and get Interval with functions

javascriptsetintervalclearinterval

提问by Greg Alexander

The code below is a sample of what I am trying to do.. on a smaller scale.This code never actually clears the interval, they just start stacking. Thanks!

下面的代码是我正在尝试做的一个示例..规模较小。这段代码实际上从未清除间隔,它们只是开始堆叠。谢谢!

<script>
var num = 0;
var counter = setInterval('start_count()',1000);

function start_count(type){
    num++;
    document.getElementById('num_div').innerHTML = num;
}
function stop_count(){
   clearInterval(counter);
   num = 0;
}
</script>
<div id="num_div"></div>
<br>
<input type="button" value="Stop" onClick="stop_count()">
<input type="button" value="Start" onClick="counter = setInterval('start_count()',1000)">

Please Help!

请帮忙!

回答by Elias Van Ootegem

Please, don'tpass a string to setInterval, JS functions are first-class objects, so they can be passed as arguments, assigned to variables or returned by other functions. In your example, I'd write the following:

不要将字符串传递给setInterval,JS 函数是一等对象,因此它们可以作为参数传递、分配给变量或由其他函数返回。在您的示例中,我将编写以下内容:

<input type="button" value="Start" id="intervalStart"/>
<input type="button" value="Start" id="intervalStop"/>

And then, the JS:

然后,JS:

window.onload = function()//not the best way, but just as an example
{
    var timer, num = 0, 
    numDiv = document.getElementById('num_div');//<-- only scan dom once, not on every function call
    document.getElementById('intervalStart').onclick = function(e)
    {
        this.setAttribute('disabled','disabled');//disable start btn, so it can't be clicked multiple times
        timer = setInterval(function()
        {
            numDiv.innerHTML = ++num;
        },1000);
    };
    document.getElementById('intervalStop').onclick = function(e)
    {
        document.getElementById('intervalStart').removeAttribute('disabled');//enable start again, you could do the same with disable btn, too
        clearInterval(timer);
        num = 0;
        numDiv.innerHTML = '';
    };
};

This code needs some more work, though at least it doesn't pollute the global namespace too much.
Do note that I've used a variable to reference the num_divelement, that way your interval callback function doesn't have to scan the entire DOM for that element every 1000ms. It's not much, but keep in mind that every time you use a jQuery selector, or a getElement(s)By*method, JS hasto traverse the DOM and look for the element. Keeping a reference to an element you'll be needing a lot just makes for a more efficient script.

这段代码需要做更多的工作,但至少它不会过多地污染全局命名空间。
请注意,我使用了一个变量来引用num_div元素,这样您的间隔回调函数就不必每 1000 毫秒扫描一次该元素的整个 DOM。不多,但请记住,每次使用 jQuery 选择器或getElement(s)By*方法时,JS必须遍历 DOM 并查找元素。保留对您非常需要的元素的引用只会使脚本更高效。

回答by Josep

I think that this code will do what you were trying to do:

我认为这段代码会做你想做的事情:

<script>
    var num = 0;
    var counter;

    function start_interval() {
        counter = setInterval(function () { start_count() }, 1000)        
    }

    function start_count() {
        num++;
        document.getElementById('num_div').innerHTML = num;
    }
    function stop_count() {
        clearInterval(counter);
        num = 0;
    }
</script>
<div id="num_div"></div>
<br>
<input type="button" value="Stop" onClick="stop_count();">
<input type="button" value="Start" onClick="start_interval();"> 

回答by Matt Burland

Not clear exactly what the problem is. Your code works fine (aside from the comments about passing strings to setInterval). If your problem is that hitting "start" multiple times adds multiple intervals, then yeah. You can fix that by checking if the clock is already running.

不清楚具体是什么问题。您的代码工作正常(除了关于将字符串传递给 setInterval 的注释)。如果您的问题是多次点击“开始”会增加多个间隔,那么是的。您可以通过检查时钟是否已经在运行来解决这个问题。

Here's an example:

下面是一个例子:

function startCounter() {
    if (!counter) {
        counter = setInterval(start_count,1000);
    }
}

function start_count(type){
    num++;
    document.getElementById('num_div').innerHTML = num;
}

function stop_count(){
   clearInterval(counter);
   counter = 0;
   num = 0;
}

Here's a fiddle

这是一把小提琴

回答by Brad Christie

<script>
    var num = 0;
    var counter = setInterval(start_count,1000);  
    function start_count(type){     
        num++;     
        document.getElementById('num_div').innerHTML = num;
    }
    function stop_count(){    
        clearInterval(counter);    
        num = 0;
    }
</script>
<div id="num_div"></div>
<br>
<input type="button" value="Stop" onClick="stop_count()">
<input type="button" value="Start" onClick="counter = setInterval(start_count,1000)">

That's the working version. But as mentioned in the comments, one of two things should be passed to a setIntervalor setTimeout:

那是工作版本。但正如评论中提到的,应该将两件事之一传递给 a setIntervalor setTimeout

A function which defines the code that should be executed:

定义应该执行的代码的函数:

setTimeout(function(){
  /* timeout code */
}, 1000);

Or a reference to the function that you want to call (exempting the quotation marks):

或对您要调用的函数的引用(不包括引号):

function myTimeoutFunction(){
  /* timeout code */
}
setTimeout(myTimeoutFunction, 1000);