I want to make a counter that will count(and add up) each second. I'm trying to do it with the timing events but it doesn't work
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script type="text/javascript">
var i=0;
function Time(){
seconds = setInterval(function(){
i++;
}, 1000);
return {label:seconds};
}
console.log(setTimeout(Time, 1000));
</script>
</body>
</html>
it just shows the first iteration and also it starts from 2 instead of 1...
6 Answers 6
setTimeout and setInterval return the handle to the timer events as soon as it is called - not the value as you expect.
If you want to retrieve the value you will need to utilise either callbacks, global variables etc.
Comments
Your solution prints the output of setTimeout, which is the timeout identifier. This will work:
var i = 0;
function Time()
{
i ++;
console.log(i);
}
setInterval( Time, 1000 );
Comments
That's because you're only logging the result value of the first call to your Time method. Additionally you're assigning secondsto the return value of setInterval which returns an id.
If you want to return a value each second, update your code to:
var _seconds = 0;
function Time(callback){
setInterval(function(){
callback(++_seconds);
}, 1000);
}
Time(function(seconds){
console.log(seconds);
});
Comments
setTimeout will return the timer id not the return value.Try this
setInterval(function () {
console.log(++i);
}, 1000);
Comments
Here, setInterval does not returns the value for seconds instead it gives the id.
You need only setInterval:
var count = document.getElementById('count');
var i = 0;
setInterval(function() {
count.innerHTML = i;
i++;
}, 1000);
<div id='count'>--</div>
Using clearInterval:
var count = document.getElementById('count');
var i = 0;
var id = setInterval(function() {
count.innerHTML = i;
i++;
if (5 < i)
clearInterval(id);
}, 1000);
<div id='count'>--</div>
Comments
thanks all for the helpful input. i modified the code to what i had in mind:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script type="text/javascript">
var i=0;
function Time(){
i++;
console.log(i);
setTimeout(Time, 1000);
}
Time();
</script>
</body>
</html>
SetIntervalwill return the ID value that can be used toclearInterval. Why are you mapping it toseconds?