简体   繁体   中英

How can I display a timer counting for 10 seconds

I have this Javascript code in my website:

<!DOCTYPE html>

<html>
   <head>
      <title>change picture</title>
      <script type = "text/javascript">
          function displayNextImage() {
              x = (x === images.length - 1) ? 0 : x + 1;
              document.getElementById("img").src = images[x];
          }

          function displayPreviousImage() {
              x = (x <= 0) ? images.length - 1 : x - 1;
              document.getElementById("img").src = images[x];
          }

          function startTimer() {
              setInterval(displayNextImage, 10000);
          }

          var images = [], x = -1;
          images[0] = "http://newsxpressmedia.com/files/theme/radar000116.Gif";
          images[1] = "http://newsxpressmedia.com/files/theme/radarClosed.gif";
      </script>
   </head>

   <body onload = "startTimer()">
       <img id="img" src="http://newsxpressmedia.com/files/theme/radar000005.Gif">
       <button onclick="displayPreviousImage()">Previous</button>
       <button onclick="displayNextImage()">Next</button>
   </body>
</html>

I want above each image to show the timer counting the seconds to 10 in this format 00:00 The first 00 for minutes and the second 00 for seconds.

In this case there is only seconds but I want to show 00:00 and only the right 00 will be counting since it's only seconds now.

And every 10 seconds the timer will reset and the shown image will change.

Ok then, try using this code it will help you :

JAVASCRIPT:

var counter = 0;

setInterval(function () {
if (counter<10)
++counter;
else counter =0;
document.getElementById("count").innerHTML="00:"+counter;
}, 1000);

HTML:

<p id="count"></p>

You can test it here .

Edit:

And to make it fit your question try to use this function:

function swap(one, two) {
document.getElementById(one).style.display = 'block';
document.getElementById(two).style.display = 'none';
}

And your code will be:

setInterval(function () {
if (counter<10){
    ++counter;
} else {
    counter =0;
    swap(one,two);
}
    document.getElementById("count").innerHTML="00:"+counter;
}, 1000);

And "one" and "two" here are the ids of your imgages tags.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM