0

Trying to display the values of my inner HTML, from 10 to 1, but am able to show only the value 1.

the values should display, one by one.. For example if 10 get displays, it should hide and then 9 should display, it just like a timer.

How to fix this, this is what I have tried.

HTML:

<div id='test'></div>

JS:

var a = 10;
var b=1;
var tar = document.getElementById('test');

for(var a=10;a>=b;a--){
    tar.innerHTML = a;    
    if(a==b){
        tar.innerHTML = a;
        //tar.style.display='none';
        window.location.href = "http://www.google.co.in";
    }
}

fiddle demo

0

4 Answers 4

1

The problem you have is that JavaScript can execute incredibly fast, so it is counting from 10 to 1 faster than you can see. You need to slow it down a little with a timer...

In this example, there is a one second delay between each number.

var a = 10;
var b = 1;
var tar = document.getElementById('test');
var timer;

function countDown() {
    tar.innerHTML = a;    
    if(a === b) {
        tar.innerHTML = a;
        //tar.style.display = 'none';
        window.location.href = "http://www.google.co.in";
    } else {
        a--;
        timer = window.setTimeout(countDown, 1000);
    }
}

countDown();
Sign up to request clarification or add additional context in comments.

2 Comments

@SteveFenton: How the user may know that the timer is started, its not showing on the page..
The timer shows in the <div id='test'></div> tag you already have.
0
<html>
<head>
    <script>
    var myVar = setInterval(function(){myTimer()}, 1000);
    var i=10;
function myTimer() {
    i--;
    if(i==1)
        clearInterval(myVar);
    document.getElementById("test").innerHTML = i;

}
</script>
</head>
<body>
 <div id="test"></div>
</body>
</html>

2 Comments

When you are finished in this example, you should use window.clearInterval(myVar) to stop the timer executing. You can also use the shorter setInterval(myTimer, 1000).
You can use clearInterval(myVar); instead of return false; in if condition so that timer will stop.
0

You can simply do:

var counter = 10; // number of iterations
var tar = document.getElementById('test');    
var interval = setInterval(function(){
    if (counter === 0) clearInterval(interval); // skip if reached end
    tar.innerHTML = counter; // update html
    counter--; // update counter value
}, 1000) // 1000 = 1 second

See Fiddle

Comments

0

http://jsfiddle.net/0sbu5f8c/13/

var a = 10;
var b = 1;
var tar = document.getElementById('test');
var timer = setInterval(function () {
    tar.innerHTML = a;
    if(a === b) {
        window.clearInterval(timer);
        //window.location.href = "http://www.google.co.in";
    }
    a -= 1;
}, 500);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.