0

I'm trying to implement basic 60 sec counter(A p element with idcounter), that is triggered after a button(counter_start()) is pressed.But I want delay of 1 sec between this and make sure this updates in browser window in real-time

 <script type="text/javascript">

    function counter_start(){
        x=0
        for(i=0;i<60;i++){
        x++;
        document.getElementById("counter").innerHTML=x;

         }
     }


    </script>

P.S: There might be other simple methods of implementing a timer.But it's not about timer...actually I'm a student and trying to figure out the architecture and mechanism of this. EDIT: please post tested versions of the code, as some of em' posted below DO NOT update in real time

2
  • You cant delay a for loop in and of itself, you will have to implement your own version of the for loop. Nov 17, 2014 at 11:30
  • You should accept Parth's answer. All you need to do is replace alert(i) with document.getElementById("counter").innerHTML=i Nov 17, 2014 at 11:40

6 Answers 6

3

Try this Example Hope it will work for u

JS

 for(i = 1; i <= 3; i++)
   {
   (function(i){
       setTimeout(function(){
         alert(i);
     }, 1000 * i);
   }(i));
} 
1
  • 1
    This method proves a good understanding of the language. Nice Nov 17, 2014 at 11:35
1

Javascript operates synchronously in the browser.

You need to use setTimeout or setInterval to schedule the for loop's body to be called every second. I'm using setTimeout in the below example for easier "garbage collection"; we will never reschedule the tick to happen after we don't need to update things anymore.

<script type="text/javascript">

var counter = 0;

function counter_tick() {
    if(counter < 60) {
        counter++;
        document.getElementById("counter").innerHTML = counter;
        setTimeout(counter_tick, 1000); // Schedule next tick.
    }
}

function counter_start() {
    counter_tick(); // First update, also schedules next tick to happen.
}


</script>   
0

It sounds like you are looking for a way to pause the current thread, which isn't possible in JavaScript and would probably be a bad idea anyway (the user's browser would lock up while the thread was paused).

A timer is really the way to go with this, otherwise you are fighting the way the language is intended to work.

0

There is no sleep-function in JS. But you can use window.setTimeout to call a function in given intervals:

function counter_start(){
    // get current value
    var value = document.getElementById("counter").innerHTML*1;
    // leave function if 60 is reached
    if(value == 60) {
         return;
    }
    // set the innerHTML to the last value + 1
    document.getElementById("counter").innerHTML=value+1;
    // call next iteration
    window.setTimeout(function(){counter_start()}, 100);
}

counter_start();

JSFiddle-Demo

1
  • Why do you have counter_start() inside of its own function? Should just be window.setTimeout(counter_start, 100); Nov 17, 2014 at 11:33
0

For-loops run to completion, so you wouldn't usually use one for this. You just need a timer and a variable to increment:

var maketimer = function(){
    var tick = 0,
        interval_ms = 1000,
        limit = 10,
        id;
    return {
        start: function(){
            var timer = this;
            console.log('start');
            id = setInterval(function(){
                if(tick === limit){
                    timer.stop();
                    timer.reset();
                    return;
                }
                tick += 1;
                console.log(tick);
            }, interval_ms);
        },
        stop: function(){
            console.log('stop');
            clearInterval(id);
        },
        reset: function(){
            console.log('reset');
            tick = 0;
        }
    };
};

var t = maketimer();
t.start();

If you really need to use a for-loop, then you could use a generator function. They're part of the proposed ES6 spec., and you'll need Firefox 26+ to try this out. However the only point of doing this would be to learn about generator functions.

var maketimer = function(){
    var interval_ms = 1000,
        limit = 10,
        id,
        loop,
        it;
    loop = function*(){
        var i;
        for(i=1; i<=limit; i+=1){
            yield i;
        }
    };
    it = loop();
    return {
        start: function(){
            var timer = this;
            console.log('start');
            id = setInterval(function(){
                var tick = it.next();
                console.log(tick.value);
                if(tick.done){
                    timer.stop();
                    timer.reset();
                    return;
                }
            }, interval_ms);
        },
        stop: function(){
            console.log('stop');
            clearInterval(id);
        },
        reset: function(){
            console.log('reset');
            it = loop();
        }
    };
};

var t = maketimer();
t.start();

0

Try this::

var x=0;
var myVar;
function myTimer() {
    x++;        
    document.getElementById("counter").innerHTML = x;
    if(x==60)
        clearInterval(myVar);
}
function counter_start(){
    myVar=setInterval(function(){myTimer()},1000);
 }

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.