Reputation: 55
I have tried everything, I can't do it!!! Here's my code please help:
<!DOCTYPE html>
<html>
<head>
<link rel="shortcut icon" href="favicon.ico"/>
<title>Doughtnut Box !</title>
<!--Design-->
<style>
</style>
<!--jQuery and Javascript-->
<script>
var doughnut = 0;
window.setInterval(
doughnut + 1
,1000);
document.getElementById("doughnuts").innerHTML="You have " + doughnut >+ " doughnuts!";
</script>
</head>
<body>
<h3 id="doughnuts"></h3>
</body></html>
Thanks for the code, it was really great! Now how can I save it so that it won't start over when I refresh?
Upvotes: 4
Views: 14171
Reputation: 135772
Put them in a function. Also, change your expression to an assignment.
<script>
var doughnut = 0;
window.setInterval(
function () {
doughnut = doughnut + 1;
document.getElementById("doughnuts").innerHTML = "You have " + doughnut + " doughnuts!";
}, 1000);
</script>
Runnable demo below:
var doughnut = 0;
window.setInterval(function () {
doughnut = doughnut + 1;
document.getElementById("doughnuts").innerHTML = "You have " + doughnut + " doughnuts!";
}, 1000);
<div id="doughnuts"></div>
Upvotes: 10
Reputation: 582
Another way which count the time to do the function.
This case is not relevant but it may be usefull under certains circumptances.
var doughnut = 0;
function show_value()
{
document.getElementById("doughnuts").innerHTML = "You have " + doughnut++ + " doughnuts!";
setTimeout(show_value, 1000);
}
show_value();
Upvotes: 1
Reputation: 4735
Try this:
var doughnut = 0;
window.setInterval(
function()
{
document.getElementById("doughnuts").innerHTML="You have " + ++doughnut + " doughnuts!";
}
,1000);
Upvotes: 1
Reputation: 15699
Try this:
var doughnut = 0;
//show 0 for the first time
show_value();
//start counter
setInterval(function(){
doughnut += 1;
show_value();
}, 1000);
function show_value(){
document.getElementById("doughnuts").innerHTML = "You have " + doughnut + " doughnuts!";
}
Upvotes: 1
Reputation: 16140
setInterval
accepts function or quoted code.
Try that:
<script>
var doughnut = 0;
window.setInterval(function(){
doughnut++;
document.getElementById("doughnuts").innerHTML = "You have " + doughnut + " doughnuts!";
}, 1000);
</script>
Upvotes: 2