JavaScript: Display Auto Counter
Blogs20142014-08-20
Display Auto Counter
I wrote an interesting example to auto increment a number. The following is the code:
`//suppose we have a <div id="Counter">Counter</div>:
//$(’
‘).attr(‘id’, ‘Counter’).html(‘Counter’).prependTo(‘body’); // After that: var start=100, end=110, divId = ‘Counter’; var increment = (function() { var i = start || 100; return function() { return i++; } }());var myVal = setInterval(function() { var count = increment(); if (count>end) { stopIncrement(myVal); return; } document.getElementById(divId).innerHTML = count; }, 1000);
function stopIncrement(thisVal) { clearInterval(thisVal); }`
In the above example, the number will start from 100; auto increment by 1 in every second; and terminate when the number is 110.
Another example to display the current time is from w3schools.com:
`var myVar = setInterval(function(){myTimer()}, 1000);
function myTimer() { var d = new Date(); var t = d.toLocaleTimeString(); document.getElementById(“Counter”).innerHTML = t; }`
The setInterval() method will execute the function once every 1 second, just like a digital watch.