SetTimeout with standard counter

前端 未结 4 1546
北恋
北恋 2021-01-29 03:59

I want to create a alert \"Hello\" which will show up after 10sec. I used setTimeout and it working fine. Now i would like to do counter(timer) which will show 10, 9, 8,7 ...

相关标签:
4条回答
  • 2021-01-29 04:02

    You can do something like that:

    var count = 10; 
    var timer = function(){
      setTimeout(function(){
        alert(count);
        if(count == 0){
          //do something
        }
        else{
          count--;
          timer();
        }
      }, 1000);
    }
    

    To run just:

    timer();
    
    0 讨论(0)
  • 2021-01-29 04:10

    You'll have to make one, setInterval would be a good choice for counter.

    var time = 10, x = setInterval(function () {
      console.log(--time);
      if (time === 0) {
        alert("hello");
        clearInterval(x);
      }
    }, 1000);
    
    0 讨论(0)
  • 2021-01-29 04:16

    The setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds).

    you can stop evaluates by clearTimeout() function.

    Try the code

    <p></p>
    
    <script>
        var sObj = setInterval(function(){
         var obj = document.getElementsByTagName("p")[0];
            if(obj.innerHTML == "0"){
                alert("hello");
                clearTimeout(sObj);
            }
            if(obj.innerHTML == ""){
              obj.innerHTML = 10;
            }else{
                var cur = parseInt(obj.innerHTML); 
              obj.innerHTML = cur - 1;
            }   
    </script>
        }, 1000)
    
    0 讨论(0)
  • 2021-01-29 04:18

    Simple variant:

    var count=10;
    
    var counter=setInterval(timer, 1000);
    
    function timer()
    {
      count=count-1;
      if (count <= 0)
      {
         clearInterval(counter);
          alert("Finished!")
         return;
      }
    
     document.getElementById("timer").innerHTML=count + " secs"; // watch for spelling
    }
    

    Working jsfiddle

    0 讨论(0)
提交回复
热议问题