制作一个简单的javascript计时器

时间:2017-05-05 03:49:53

标签: javascript

嘿,我正在尝试为不和谐API(javascript)上的应用程序制作一个小的20秒计时器...我在网上得到了很多答案,但似乎没有一个证明是成功的。谁能帮我?这是我最初编写的代码

            setTimeout(function(){ var af = 0; while(af<21){ af = af+1;  if(af == 20){ break; } console.log(af);} }, 1000);
            message.reply("check the console"); // Part of the discord.js library...nothing to do with the timer

但是var af并没有每秒减少一次......它在不到一秒的时间内就变成了20 ......但是setTimeout()没有得到跟踪......你能帮助我吗?

4 个答案:

答案 0 :(得分:1)

你的问题不明确。 你想让af每秒减少或增加1吗?

如果你希望af从20开始每秒减少1并从0结束。

 var af = 20; 

a = setInterval(function(){ 
console.log("Hi");
af = af-1;

if(af == 0){ 
    clearInterval(a);
 } 
console.log(af);
}, 1000);

这将每秒调用该函数。

答案 1 :(得分:0)

如果你想每X秒做一些事情,你可以使用setInterval。

setInterval(function(){ 
  //code goes here that will be run every 1 seconds.    
}, 1000);

如果您想做一次但有延迟的话,可以使用setTimeout

setTimeout(function() {
  //code will run after 30 seconds  
}, 30000);

所以我猜你想做这样的事情:

var af = 20;
function myTimer() {
  if(af === 0) {
    message.reply("check the console");
    clearInterval(timer);
  } else {
    af = af - 1;
    console.log(af);
  } 
}

var timer = setInterval(function(){ myTimer() }, 1000);

或者只使用setTimeout

setTimeout(function() {
  message.reply("check the console");
}, 20000);

答案 2 :(得分:0)

 <script Src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="random_no_container">
Hello. Here you can see random numbers after every 60 sec

<script>
window.setInterval(function(){
             /// U CAN DO YOUR CODE HERE
          var ran=Math.random();
          jQuery('#random_no_container').html(ran);
          }, 3000);
</script>

答案 3 :(得分:0)

您似乎对setTimeout方法的工作方式存在误解,并且在更大程度上误解了函数执行的工作原理。运行以下代码:

setTimeout(function() { 
  var af = 0; 
  while(af<21){ 
    af = af+1;  
    if(af == 20){ break;} 
    console.log(af);
  } 
}, 1000);

setTimeout1000 ms之后调用该函数。然后完成它的执行,只运行一次。此外,你必须考虑你的功能本身在做什么;当它在1000 ms之后调用时,它会遍历整个块,将af设置为0,然后循环直到其20然后退出,无论其构造如何维护任何af的持久性;功能完成后af不再存在。 你需要做的是在改变它的函数范围之外声明af,并且每次迭代只改变一次。一种常见的方法是将setTimeout置于函数内并递归调用它,直到满足已停止的条件。请考虑以下代码:

    var af = 0;
    function delayIncrementAF() {
        if(af == 20){return;}
        setTimeout(function () {
             af = af+1;  
             console.log(af);
             delayIncrementAF();
       }, 1000);
    }
    delayIncrementAF();

相关问题