-3

I have this timer on my website and I use the script below to change the date and time.

I would like to make some edits so it automatically resets every day at 12am.

Also, I want the script to check the time on the client side and reset depending on the time of the user.

Can someone please help?

<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>
Andrilio
  • 1
  • 3
  • Possible duplicate of [Stop setInterval call in JavaScript](http://stackoverflow.com/questions/109086/stop-setinterval-call-in-javascript) –  Nov 21 '16 at 10:33

2 Answers2

5

With clearInterval() First create a reference, then you can clear it:

var ref = setInterval(...

... 

clearInterval(ref);

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

Salmin Skenderovic
  • 1,750
  • 9
  • 22
1

You need to assign your setInterval to a variable, which you can then use in a call to clearInterval, like so:

var timer = setInterval(....

and to clear it:

clearInterval(timer);
Stuart
  • 6,630
  • 2
  • 24
  • 40