最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Make a timer using setInterval() - Stack Overflow

programmeradmin4浏览0评论

I'm trying to make a timer in javascirpt and jQuery using the setInterval function. The timer should count down from 90 to zero (seconds).

The code that I'm using for this:

setInterval(settime(), 1000);

in this settime() sets the var time (started on 90) -1, this action has to happen once every second. My problem is that I don't get how to let this action happen 90 times; I tried using a for loop but then the counter counts from 90 to 0 in 1 second.

Does anyone knows a better alternative?

I'm trying to make a timer in javascirpt and jQuery using the setInterval function. The timer should count down from 90 to zero (seconds).

The code that I'm using for this:

setInterval(settime(), 1000);

in this settime() sets the var time (started on 90) -1, this action has to happen once every second. My problem is that I don't get how to let this action happen 90 times; I tried using a for loop but then the counter counts from 90 to 0 in 1 second.

Does anyone knows a better alternative?

Share Improve this question edited May 24, 2015 at 20:36 Antonio Laguna 9,2927 gold badges37 silver badges72 bronze badges asked May 24, 2015 at 20:15 Benjamin753Benjamin753 1151 gold badge1 silver badge5 bronze badges 1
  • 1 You must pass a function, not call it! Just setInterval(settime, 1000), no settime()! – Bergi Commented May 24, 2015 at 20:58
Add a ment  | 

4 Answers 4

Reset to default 5

Something like this should do the trick:

var count = 90;
var interval = setInterval(function(){
  setTime();
  if (count === 0){
    clearInterval(interval); // Stopping the counter when reaching 0.
  }
}, 1000);

I don't have the code you need but I'm sure you'll need to update the count at some point on your page.

You can cancel an interval with clearInterval which needs the ID of the interval that's created when you call setInterval

function timer(seconds, cb) {
  var remaningTime = seconds;
  window.setTimeout(function() {
    cb();
    console.log(remaningTime);
    if (remaningTime > 0) {
      timer(remaningTime - 1, cb); 
    }
  }, 1000);
}

var callback = function() {
  console.log('callback');
};

timer(90, callback);

Caution in using setInterval, may not work as you expect http://bonsaiden.github.io/JavaScript-Garden/#other.timeouts

setInterval keeps calling your function at each second (since you use 1000).

So setInterval expects a function as its first argument, which is the function which will be called periodically. But instead of passing settime, you pass its returned value. That won't work, unless settime returns a function.

Instead, try

setInterval(settime, 1e3);

Try utilizing .data() , .queue() , animate() , .promise() ; to stop "countdown" can call $(element).clearQueue("countdown")

var counter = function counter(el) {
   return $(el || window).data({
    "start": {
      "count": 0
    },
    "stop": {
      "count": 1
    },
    "countdown": $.map(Array(90), function(val, key) {
                   return key
                 }).reverse(),
    "res": null
  })
  .queue("countdown", $.map($(this).data("countdown")
    , function(now, index) {
      return function(next) {
        var el = $(this);
        $($(this).data("start"))
        .animate($(this).data("stop"), 1000, function() {
          el.data("res", now)
          $("pre").text(el.data("res"));
          next()
        });
      }
    })
  )
  .promise("countdown")
  .then(function() {
    $("pre").text($(this).data("res"))
    .prevAll("span").text("countdown plete, count:");
  });
  };
  $("button").on("click", function() {
    if ($(this).is("#start")) {  
       counter();
       $("pre").text(90).prev("span").html("");
       $(window).dequeue("countdown");
    }
    else {
       $(window).clearQueue("countdown").promise("countdown")       
      .then(function() {
         $("pre").prevAll("span").html(function(_, html) {
         return html.replace("plete", "stopped")
       });
       })       
    }
  });
pre {
  font-size:36px;
}
<script src="https://ajax.googleapis./ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<button id="start">start</button><button id="stop">stop</button>
<br />
<span></span>
<br />
<pre>90</pre>

发布评论

评论列表(0)

  1. 暂无评论