javascript 从 10 开始倒计时,并在计时器响应为 0 时重复此操作

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

Count down from 10 and repeat it when the timer has reacted 0

javascriptjquerycountdown

提问by Erik

I want to count down from 10 seconds to 0. When it have reached 0 the DIV will reload and the timer will start over again. I have this function that allows it to do exactly like I wanted but the problem is that when the countdown have reached 0 and going back to 10, it will count -1 reload-2 reload-3 reload-4 reloadand so on. That is nothow I want it! :)

我想从 10 秒倒计时到 0。当它达到 0 时,DIV 将重新加载并且计时器将重新开始。我有这个功能可以让它完全按照我想要的方式做,但问题是当倒计时达到 0 并回到 10 时,它会计数 -1重新加载-2重新加载-3重新加载-4重新加载等等。这不是我想要的!:)

Here's my code:

这是我的代码:

var time = setInterval(countdown, 1000);
function countdown() {
    var count = 10;
    countdown = setInterval(function() {
        $('#countdown').html(count + ' sekunder kvar');

        if(count == 0) {
            $('#weather-data').load('jquery-fetch/fetch-weatherdata.php?place=' + myplace);
            clearInterval(countdown);
        }

        count--;
    }, 1000);
}

How can I fix my problem so the timer counts down from 10 to 0 and repeat that countdown forever?

我该如何解决我的问题,让计时器从 10 倒计时到 0 并永远重复倒计时?

Thanks in advance.

提前致谢。

EDIT

编辑

When this function has reached 0 for the first time and starts over, it counts like this: 10, 9, 8, 10, 7, 6, 5, 4, 3, 2, 1, 10, 9, 8, 7, 10, 6, 5, 4, 3, 2, 1, 10, 9, 8, 10, 7, 6, and so on. Why does it act like this with this code?

当这个函数第一次达到0并重新开始时,它的计数是这样的:10, 9, 8, 10, 7, 6, 5, 4, 3, 2, 1, 10, 9, 8, 7, 10 , 6, 5, 4, 3, 2, 1, 10, 9, 8, 10, 7, 6, 等等。为什么这段代码会这样?

function countdown() {
    var count = 10;
    var timerId = setInterval(function() {
        $('#countdown').html(count + ' sekunder kvar');
        count--;

        if(count == 0) {
            $('#weather-data').load('jquery-fetch/fetch-weatherdata.php?place=' + myplace);
            clearInterval(timerId);
            countdown();
        }
    }, 1000);
}

countdown();

Thanks in advance!

提前致谢!

回答by Andreas Wong

I see a lot of problems in your script... So not sure how you even get that to work..

我在你的脚本中看到了很多问题......所以不知道你是如何让它工作的......

  1. Function name can't have -, so that call won't work :S
  2. countdownis a global variable inside your function countdown()which is the same as your function name, effectively a countdownception
  3. You are effectively creating a new Intervalevery one second as you are calling countdown
  1. 函数名不能有-,所以调用不起作用:S
  2. countdown是您内部的一个全局变量function countdown(),与您的函数名称相同,实际上是一个countdownception
  3. Interval当你打电话时,你每一秒都在有效地创造一个新的countdown

To achieve what you want, try the simpler:

要实现您想要的,请尝试更简单的:

function countdown() {
    // your code goes here
    var count = 10;
    var timerId = setInterval(function() {
        count--;
        console.log(count);

        if(count == 0) {
            // your code goes here
            count = 10;
        }
    }, 1000);
}

countdown();

http://jsfiddle.net/Xrbm5/13/

http://jsfiddle.net/Xrbm5/13/

回答by Niet the Dark Absol

Take a look at what your code is doing.

看看你的代码在做什么。

You are setting an interval to run every second. That's fine.

您正在设置一个间隔以每秒运行一次。没关系。

What isn't fine is that, every second, that interval is creating a NEW interval that individually counts down from 10.

不好的是,该间隔每一秒都在创建一个新的间隔,该间隔从 10 开始单独倒计时。

Also, you are setting countdownas a global variable. So when your first counter reaches zero, it actually clears the LAST timer, leaving the first one to happily continue into negative numbers, all the while you're spawning new intervals.

此外,您正在设置countdown为全局变量。因此,当您的第一个计数器达到零时,它实际上会清除 LAST 计时器,让第一个计时器愉快地继续变为负数,而您一直在产生新的间隔。

Overall, it's a disaster.

总的来说,这是一场灾难。

回答by RobG

If you just want to update the page every 10 seconds, then:

如果您只想每 10 秒更新一次页面,则:

setTimeout(function() {
   // run some code
},10000);

If you want a count down, then reset just the counter at each even number of 10. The following adds start and stop functions, it re-stats from where it left off. Also, if running, clicking start doesn't start another one.

如果你想倒计时,然后在每个偶数 10 处重置计数器。以下添加了启动和停止功能,它从停止的地方重新统计。此外,如果正在运行,单击开始不会启动另一个。

var weatherRefresh = (function() {
  var count = 10;
  var timerRef;
  return {
    start: function() {

      // If already running, leave it running
      if (timerRef) return;

      timerRef = setInterval(function() {
        // Display count
        document.getElementById('dislayedCount').innerHTML = count;

        if (!count--) {
          // count is zero, refresh weather info
          // and start again
          count = 10;
        }
      }, 1000);
    },
    stop: function() {
      timerRef && clearInterval(timerRef);
      timerRef = null;
    }
   };
}());

And some buttons to make it work (or start it when the page loads):

以及一些使其工作的按钮(或在页面加载时启动它):

<button onclick="weatherRefresh.start();">Start</button>
<button onclick="weatherRefresh.stop();">Stop</button>

Note that the function will only run at aboutevery second, if the system is busy it will not run on time and will slowly drift, but not by much each time, so it likely doesn't matter.

请注意,该函数大约每秒运行一次,如果系统繁忙,它将不会按时运行并且会缓慢漂移,但每次都不会太多,因此可能无关紧要。