如何在Javascript上重置计时器?

时间:2016-11-21 10:28:22

标签: javascript

我的网站上有这个计时器,我使用下面的脚本来更改日期和时间。

我想进行一些编辑,以便每天早上12点自动重置。

另外,我希望脚本检查客户端的时间并根据用户的时间重置。

有人可以帮忙吗?

<script>
// set the date we're counting down to
var target_date = new Date("Nov 23, 2016 0:00:00").getTime();

// variables for time units
var days, hours, minutes, seconds;

// get tag element
var countdown = document.getElementById("countdown");

// update the tag with id "countdown" every 1 second
setInterval(function () {

// find the amount of "seconds" between now and target
var current_date = new Date().getTime();
var seconds_left = (target_date - current_date) / 1000;

// do some time calculations
days = parseInt(seconds_left / 86400);
seconds_left = seconds_left % 86400;

hours = parseInt(seconds_left / 3600);
seconds_left = seconds_left % 3600;

minutes = parseInt(seconds_left / 60);
seconds = parseInt(seconds_left % 60);

// format countdown string + set tag value
// countdown.innerHTML = days + "d, " + hours + "h, "
// + minutes + "m, " + seconds + "s";  
$('.days').html(days)
$('.hours').html(hours)
$('.minutes').html(minutes)
$('.seconds').html(seconds)


}, 1000);
</script>

2 个答案:

答案 0 :(得分:5)

使用clearInterval() 首先创建一个引用,然后你可以清除它:

var ref = setInterval(...

... 

clearInterval(ref);

http://www.w3schools.com/jsref/met_win_clearinterval.asp

答案 1 :(得分:1)

您需要将setInterval分配给变量,然后您可以在调用clearInterval时使用该变量,如下所示:

var timer = setInterval(....

并清除它:

clearInterval(timer);