mohammad ghasemi
mohammad ghasemi

Reputation: 28

Second Timer with Jquery

i have a jquery function like the below, and display resualt in span but when reload page this span hide and show for for a while . i want that not hide and show Is there a way to do this? Because I use it as a timer.!!

<span id="timer"></span>

<script>

       var counter = 61;
       var x = setInterval(function () {

           counter = counter-1;
           $('#timer').html(counter);

       },1000);

   </script>

Upvotes: 1

Views: 2518

Answers (3)

Vatsal
Vatsal

Reputation: 2128

It is because you are setting the html after one sec. Before setInterval is triggered, there is nothing present in the span.

This is what you can do

var counter = 61;
const timer = $("#timer");
timer.html(counter);
var x = setInterval(function () {
  counter = counter-1;
  timer.html(counter);
},1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="timer"></span>

https://jsfiddle.net/vatsalpande/f1kytyhz/

Upvotes: 0

Shiladitya
Shiladitya

Reputation: 12161

Start your timer from 60sec instead of 61.

var counter = 60;
$('#timer').html(counter);
var x = setInterval(function () {
  counter = counter-1;
  $('#timer').html(counter);
},1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="timer"></span>

Initialise your span with counter before setInterval.

Hope this will help you.

Upvotes: 1

Fazal Rasel
Fazal Rasel

Reputation: 4526

Initially your timer span is empty.

var counter = 61;
$('#timer').html(counter); // add this line
var x = setInterval(function () {
  counter = counter-1;
  $('#timer').html(counter);
},1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="timer"></span>

Upvotes: 0

Related Questions