user3347455
user3347455

Reputation: 51

SetTimeout with standard counter

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 ... and then alert Hello.

function counter(){
    setTimeout(function(){alert("Hello")},10000);
}

Any ideas ? Don't want any css for that. Just a standard text counter. Is there something like that ?

Upvotes: 0

Views: 1861

Answers (4)

Girish
Girish

Reputation: 12127

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)

Upvotes: 0

Farkhat Mikhalko
Farkhat Mikhalko

Reputation: 3645

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();

Upvotes: 0

Yaro
Yaro

Reputation: 568

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

Upvotes: 0

Sgoldy
Sgoldy

Reputation: 796

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);

Upvotes: 1

Related Questions