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