How do you integrate an incrementing variable into a paragraph - javascript

I am trying to make an idle game rather like candy box. I will have a number at the side of the page which rises by one every second. However, the code shown below does not seem to be working. Could anyone tell me why it is not working; how to fix it and where they got their info from. Thank you in advance.
<script type="text/javascript">
var i = 0;
function increment(){
i++;
document.getElementById('money').innerHTML = i;
}
setInterval(increment(), 1000);
</script>
<h2><u>The best game of the century</u></h2>
<p>you have £<span id="money"></span>.</p>
</body>
</html>

You have two issues:
You are calling your script before the DOM is rendered, so at the point the script runs, there is no element with ID of money.
In your setInterval call, you only need the function name (increment) without the parentheses. Including the parentheses (as increment()) only calls the function at that specific moment, rather than referencing it to be called at each interval. (See the Microsoft page on setInterval for more detailed information.)
See this code:
<h2><u>The best game of the century</u></h2>
<p>you have £<span id="money"></span>.</p>
<script type="text/javascript">
var i = 0;
function increment() {
i++;
document.getElementById('money').innerHTML = i;
}
setInterval(increment, 1000);
</script>

change setInterval(increment(), 1000); to setInterval(increment, 1000);
Its not working because as per document https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval
it takes a function reference to be executed.. but calling the function increment() like this will only execute once and the return of that function will be used which will be null and not intended hope this clears it
var i = 0;
function increment(){
//console.log(i);
i++;
document.getElementById('money').innerHTML = i;
}
setInterval(increment, 1000);
<h2><u>The best game of the century</u></h2>
<p>you have £<span id="money"></span>.</p>

Related

How to initiate a setInterval function with 0 sec but repeat it for a given time?

I'm currently using a setInterval function so that I can repeat text with an extra letter added to it for every 5 secs, hence I've set the time period for the setInterval function as 5000.
But I also want this function to be executed as soon as the page loads. To be clear the logic present inside the setInterval function should be executed as soon as the page loads and it should also be repeated for every 5 secs. Is it possible with setInterval function or else is there any other way to do it? Thank you in advance :)
setInterval(function(){
var x = document.getElementById('sample');
x.innerHTML = x.innerHTML+'L';
},5000);
<p id="sample">Sample Text</p>
Just make it a separate function, which you can then call right away. On top of that, you'll then have some nice reusable code:
function updateElement(){
var x = document.getElementById('sample');
x.innerHTML = x.innerHTML+'L';
}
setInterval(updateElement, 5000);
updateElement();
<p id="sample">Sample Text</p>
You can use named function run on init and call it each interval
setInterval(function someFunc() {
var x = document.getElementById('sample');
x.innerHTML = x.innerHTML + 'L';
return someFunc
}(), 1000);
<div id="sample"></div>

Updating an interval variable on screen in the HTML

In the head section:
var countdownTimer; <br/>
countdownTimer = 45; <br/>
function makeCountdown() { <br/>
countdownTimer = countdownTimer - 1; <br/>
}
setInterval(makeCountdown, 1000);
<br/><br/>
In the body section of the page:
document.write(countdownTimer);<br/>
function updateCountdown() { <br/>
document.replace(countdownTimer); <br/>
}
<br/><br/>
setInterval(updateCountdown, 1000);
<br/><br/>
I've checked in the browser console and the countdownTimer variable goes down each second, but where I'm struggling is on how to update the variable on the page in real time.
I've had a long look and I can't find anything here or elsewhere online that can help me out, I'm also fairly new to javascript. Many thanks for any help!
Make changes to the Element rather than document itself
There is no replace method for document
There is no point having 2 intervals if duration is identical
Note: Make sure you place script as last child of body or else, DOM api will try toa ccess the element before DOM is ready which will return null result for document.getElementById('elem')
var countdownTimer;
var elem = document.getElementById('elem');
countdownTimer = 45;
function makeCountdown() {
countdownTimer = countdownTimer - 1;
elem.textContent = countdownTimer;
}
setInterval(makeCountdown, 1000);
elem.textContent = countdownTimer;
<span id='elem'><span>
A little addition to Rayon's answer. To stop countdown when timer reach 0
var timer=45;
var intervalId;
function countdown(){
$('#elem').text(timer);
if(timer==0){
clearInterval(intervalId);
}
timer--;
}
intervalId=setInterval(countdown,1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<span id="elem"></span>

Converting a JavaScript Countdown to a jQuery Countdown and adding an Interval

I found this JS-Countdown Script at JSFiddle.
EDIT:
I'm using the code of rafaelcastrocouto now, which is nearly perfect. I wanted a 10-seconds JQuery Countdown-Script with an interval that resets the countdown timer at 5 seconds and starts over again and again, but only for a specific class with a specific id on the whole HTML page. If it drops to 0, the countdown should stop. Also I want to reset specific counters to 10.
It's about a WebSocket that refreshes every second and depending on the data I get for specific counters I want to reset them or they should count down to zero.
New JSFiddle: http://jsfiddle.net/alexiovay/azkdry0w/4/
This is how I solved with jquery and native setInterval...
var setup = function(){
$('.count').each(eachSetup);
};
var eachSetup = function(){
var count = $(this);
var sec = count.data('seconds') ;
count.data('count', sec);
};
var everySecond = function(){
$('.count').each(eachCount);
};
var eachCount = function(){
var count = $(this);
var s = count.data('count');
count.text(s);
s--;
if(s < 0) {
s = count.data('seconds');
}
count.data('count', s);
};
setup();
setInterval(everySecond, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p class="count" data-seconds="5"></p>
<p class="count" data-seconds="10"></p>
<p class="count" data-seconds="15"></p>
You have sever errors in code, e.g.
setTimeout(cd_go(id), 1000); - should point to function reference not to function execution. setTimeout also returns the timeout id. You must past that id to clearTimeout
clearTimeout(this); it should take id instead of global object (window) or undefined if you are working in strict mode
loop = setInterval(function(id) { … } - id points to undefinded as you are not passing any value for it

Slideshow Loop with JavaScript

This is the JavaScript I have for a website publishing software. This Script works fine if I want to just run the script one time.
I'm looking to add to this script to loop it and make it run over and over again.
Here is the script I have right now...
<script type="text/javascript">
var pause = 3000;
function autoPresenter(){ xr_next();
setTimeout("autoPresenter();", pause); }
setTimeout("autoPresenter();", pause);
</script>
Thank you for any assistance. The use of this is a slide show presentation that is being displayed at a trade show and I obviously don't want to be there to restart it everytime it finishes.
Cheers,
Glen
Not sure what your xr_next() is doing, but I'd use an index argument in one of your functions.
<script type="text/javascript">
var pause = 3000;
var currIndex = 0;
var itemCount = 10;
function autoPresenter()
{
if (currIndex > itemCount) currIndex = 0;
xr_next(currIndex);
currIndex++;
setTimeout(autoPresenter, pause);
}
autoPresenter();
</script>

$("#id").click(function(){calculation()});

What is wrong with the line in the header?
The below example is supposed to make a button which will increment a counter each time it is clicked. However, I enforce a delay of 2000 ms between button clicks. The version below works, however, if I use the commented out line instead of
document.getElementById("rollButton").onclick=function(){calculation()};
(both in function afterWaiting())
I get various odd results, for instance that the counter starts incrementing by a lot more than 1, and the waiting time disappears?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
function afterWaiting()
{
$("#rollButton").css("color","black");
//$("#rollButton").click(function(){calculation()});
document.getElementById("rollButton").onclick=function(){calculation()};
}
var counter=0;
function calculation()
{
////Enforcing wait:
document.getElementById("rollButton").style.color="red";
document.getElementById("rollButton").onclick="";
window.setTimeout("afterWaiting()",2000);
counter=counter+1;
document.getElementById("test").innerHTML=counter;
}
</script>
</head>
<body>
<button type="button" onclick="calculation()" id="rollButton"> Roll! </button>
<p id="test"> </p>
</body>
</html>
What have I misunderstood?
thanks in advance :)
JSFiddle:
http://jsfiddle.net/Bwxb9/
The difference is that when you apply event handlers through onclick as you do in your original version, you can only bind one handler to the element. And using onclick="" kind of clears it.
When using jQuery .click(handler) you bind a new handler each time you call it (and you can unbind it with unbind('click') (and not with onclick=""). So after a couple of calls to afterWaiting you have applied mulitple click handlers on your element, and on each click the calculation function runs multiple times..
So, one way to correct it is to replace
document.getElementById("rollButton").onclick="";
with
$('#rollButton').unbind('click');
The only code required is
<button type="button" id="rollButton"> Roll! </button>
<p id="test"> </p>
var counter = 0;
var $test = $('#test');
var $rollButton = $('#rollButton');
function increment(){
$test.html(counter++);
$rollButton.off('click', increment);
setTimeout(function(){
$rollButton.on('click', increment);
}, 2000);
}
$rollButton.on('click', increment);
Demo: Fiddle
Updated: as suggested by Andy, but I would recommend Andy's answer as it involves no additional event manipulation
var counter = 0;
var $test = $('#test');
var $rollButton = $('#rollButton');
function increment(){
$test.html(counter++);
setTimeout(function(){
$rollButton.one('click', increment);
}, 2000);
}
$rollButton.one('click', increment);
Demo: Fiddle
That's generally a bit of an odd and confusing approach.
Here's how i'd do it, without mixing jquery and pure js (onclick) too much:
http://jsfiddle.net/LGvKS/
var wait = false;
counter = 0;
$('button').click(function(){
if(!wait){
$('span').text(++counter);
wait=true;
setTimeout(function(){
wait=false;
},2000);
}
});

Categories

Resources