Accessing dynamically incremented variable JS - javascript

I'm playing around with making a little game in JS.
There's a day counter that increments every seconds through setInterval().
I would like to access the incremented variable daycount from inside the main new_game() function to trigger game events based on days that have passed.
Would appreciate if someone could help or point me in the right direction.
var day = $('#time');
var daycount = 0;
$(document).ready(function () {
$('#start').click(function () {
new_game();
$(this).addClass('disabled').html('Started');
})
});
function time() {
setInterval(function () {
daycount++;
day.html('Day ' + daycount);
return daycount;
}, 1000);
}
function new_game() {
time();
if(daycount == 5){
alert('something');
}
}

You could pass a callback function to time()
You can not return inside the setTimeout callback as there is nothing to return to.
Also as it stands now you are only checking dayCount when the new_game() is initialized....not each time it changes in the interval timer
let daycount = 0,
day = $('#day');
function time(callback) {
setInterval(function() {
daycount++;
day.html('Day ' + daycount);
callback(daycount);
}, 1000);
}
function new_game() {
function checkCount(daycount) {
if (daycount == 5) {
console.log('Is 5');
} else {
console.log('Not 5');
}
}
time(checkCount);
}
new_game()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="day">

It should be daycount not count here day.html('Day ' + daycount);
var day = $('#time');
var daycount = 0;
$(document).ready(function () {
$('#start').click(function () {
new_game();
$(this).addClass('disabled').html('Started');
})
});
function time() {
setInterval(function () {
daycount++;
day.html('Day ' + daycount);
if(daycount == 5){
alert('something');
}
//return daycount;
}, 1000);
}
function new_game() {
console.log("new_game called ");
time();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="time">...</div>
<div id="start">Click me </div>

In addition to the requested functionality:
clearInterval() is added to prevent setInterval() from counting continuously.
<input> is added so the user can set the end count.
Details commented in demo
Demo
var day = $('#time');
var daycount = 0;
$(document).ready(function() {
$('#start').on('click', function() {
/* Assign counter as the timer() function
|| running every second.
*/
var counter = setInterval(timer, 1000);
/* Define timer() function to display the
|| daycount increments as the value of
|| output#time
|| When daycount reaches the value of user
|| input of input#end, run the
|| stop() function
*/
function timer() {
daycount++;
day.val('Day ' + daycount);
if (daycount === Number($('#end').val())) {
stop();
}
}
/* Define stop() function
|| clearInterval of counter() function
|| thereby stopping the count from going 4eva
|| log the count
*/
function stop() {
clearInterval(counter);
console.log('Day ' + daycount);
}
$(this).addClass('disabled').html('STARTED');
});
});
button,
input,
output {
font: inherit
}
input {
width: 5ch
}
.disabled {
pointer-events: none
}
<input id='end' type='number' min='0' max='999'>
<button id='start'>START</button>
<output id='time'></output>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Related

I can't clear interval

I have a problem with the interval, which I can not clear after calling the function with a value.
The interval continues to increase the number and returns the percentage of the width.
Here my code:
function loadingClient(data) {
var loadingClientDiv = document.getElementById('loadingClient');
var percentageLoading = document.getElementsByClassName('percentageLoading');
var charge = 1;
var intervalLoadingClient = setInterval(barCharge, 1000);
function barCharge() {
if (charge >= 76) {
clearInterval(intervalLoadingClient);
} else {
++charge;
$(percentageLoading).css("width", charge + "%");
}
}
if (data === "100") {
clearInterval(intervalLoadingClient);
$(percentageLoading).css("width", "100%");
setTimeout(closeLoadingClient, 5000);
setTimeout(removeLoadingClient, 7000);
function closeLoadingClient() {
$(loadingClientDiv).hide("fade", 1000);
}
function removeLoadingClient() {
$(loadingClientDiv).remove();
}
}
}
loadingClient();
#hudolfhess is correct, you need to be using clearInterval instead of clearTimeout.
Also,
If you are trying to do something like this it wont work.
loadingClient() //Should start the interval.
loadingClient("100") //Should clear the interval, but doesn't.
you are trying to do? If so, you need to delcare intervalLoadingClient outside of the scope and avoid re-declaration of the variable when you call the method with parameters.
var intervalLoadingClient;
function loadingClient(data) {
var loadingClientDiv = document.getElementById('loadingClient');
var percentageLoading = document.getElementsByClassName('percentageLoading');
var charge = 1;
intervalLoadingClient = intervalLoadingClient || setInterval(barCharge, 1000);
function barCharge() {
if (charge >= 76) {
clearInterval(intervalLoadingClient);
} else {
++charge;
$(percentageLoading).css("width", charge + "%");
}
}
if (data === "100") {
clearInterval(intervalLoadingClient);
$(percentageLoading).css("width", "100%");
setTimeout(closeLoadingClient, 5000);
setTimeout(removeLoadingClient, 7000);
function closeLoadingClient() {
$(loadingClientDiv).hide("fade", 1000);
}
function removeLoadingClient() {
$(loadingClientDiv).remove();
}
}
}
loadingClient(); //Starts the interval
loadingClient("100"); //Ends the interval.

Changer SetInterval Values After Interval

If I can try to make everyone understand what I am looking for, I am looking for the value of the interval to change to lets say "5000ms" after "1000ms" and then it would go on to the next value such as "2000ms" and repeat all over again! The current code I have is pretty much a stopwatch, It adds the number 1 to a paragraph every 1000ms. Any help is extremely appreciated!
<script>
function myFunction() {
clicks += 1;
}
setInterval(myFunction, 1000);
var clicks = 0;
function myFunction() {
clicks += 1;
document.getElementById("demo").innerHTML = clicks;
// connects to paragraph id
}
</script>
<p id="demo"></p>
<!--connects to getElementById-->
Don't use setInterval - this functions will perform the action in any given interval, which you set once.
Use setTimeout instead. Which performs the action only once after given interval, and then call it again and again with different interval values.
what about this
<script>
var clicks = 0;
myFunction(1000);
function myFunction( currentInterval ) {
clicks ++;
document.getElementById("demo").innerHTML = clicks;
if ( currentInterval == 1000 )
{
currentInterval = 5000;
}
else if ( currentInterval == 5000 )
{
currentInterval = 2000;
}
else
{
currentInterval = 1000;
}
setTimeout( function(){ myFunction( currentInterval ) }, currentInterval );
}
</script>
<p id="demo"></p>
you should try using recursive timeout instead of interval
var timeout = 1000;
var timer;
function startTimer() {
clearTimeout(timer);
timer = setTimeout(function() {
console.log('tick');
startTimer();
}, timeout);
}
startTimer();
// timeout = 2000
// timeout = 500
// clearTimeout(timer); to cancel
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
This might look a little complicated but you can try something like this:
JSFiddle.
(function() {
var interval = null;
var limit = 5;
function initInterval(callback, index) {
var msToSec = 1000;
if (interval) {
clearInterval();
}
console.log("Delay: ", index)
interval = setInterval(callback, index * msToSec);
}
function clearInterval() {
window.clearInterval(interval);
interval = null;
}
function resetInterval(callback, count) {
clearInterval();
initInterval(callback, count);
}
function main() {
var count = 1;
var notify = function() {
console.log("Hello World: ", count);
var _nextCount = ((count++) % limit) + 1;
if (count < 10) {
resetInterval(notify, _nextCount);
} else {
console.log("Stoping loop...");
clearInterval();
}
}
initInterval(notify, count);
}
main()
})()

setInterval countDown update time

I have this countDown, each time I press the buttons I want to add 5 more seconds.
When the time is updated the function count down the new value but the old value as well.
Can someone explain me why?
http://jsfiddle.net/xqdj3uz8/1/
$('button').on('click', function() {
var newtime = parseInt(seconds + 5);
timer(newtime);
});
You could try by using a global variable to track the amount of seconds left. Clicking on the button will increment this variable.
var timeLeft = 10;
function timer() {
var i = setInterval(function () {
$('span').text(timeLeft);
timeLeft--
if (timeLeft === 0) clearInterval(i)
}, 1000)
}
function addSeconds(n) {
timeLeft += n
}
timer()
$('button').on('click', function () {
addSeconds(5)
});
Demo (1): http://jsfiddle.net/xqdj3uz8/21/
please use it
function timer(time) {
var interval = setInterval(countDown, 1000);
function countDown() {
time--;
$('span').text(time);
if(time === 0) {
clearInterval(interval);
}
}
$('button').on('click', function() {
time=parseInt(time + 5);
$('span').text(time);
});
}
var seconds = 5;
timer(seconds);
Try This
Working JSFIDDLE
var gblTime=0;
function timer(time) {
var interval = setInterval(countDown, 1000);
gblTime = time;
function countDown() {
gblTime--;
$('span').text(gblTime);
if(gblTime <= 0) {
clearInterval(interval);
}
}
}
var seconds = 5;
timer(seconds);
$('button').on('click', function() {
gblTime = parseInt(gblTime +1+ 5);
//timer(newtime);
});
You are adding new intervals that are independent form each other, try:
var time = 5;
var seconds = 5;
function timer() {
var interval = setInterval(countDown, 1000);
function countDown() {
$('span').text(time);
if(time === 0) {
clearInterval(interval);
}
time--;
}
}
timer();
$('button').on('click', function() {
if(time==0){
timer();
}
time += seconds;
});

clearInterval with start and stop buttons

I have a simple countdown using setinterval and I get the error that my functions are not defined. I am using the buttons to start and stop the intervals. Any ideas why this happens?
Javascript
function startCount() {
$(function() {
var count = 10;
countdown = setInterval(function() {
$("p.countdown").html(count + " seconds remaining!");
if (count === 0) {
window.location = 'http://google.com';
}
count--;
}, 1000);
});
}
function startStop() {
clearInterval(countdown);
}​
html
<p class="countdown"></p>
<button onclick="startCount()">Start</button>
<button onclick="startStop()">Stop</button>
demo
http://jsfiddle.net/54uQz/1/
Declare your countdown variable outside the startCount() function so that it is visible to both functions. At the moment it only exists in the first, so clearing the timer does nothing.
CODE:
var countdown;
function startCount() {
var count = 10;
countdown = setInterval(function() {
$("p.countdown").html(count + " seconds remaining!");
if (count === 0) {
window.location = 'http://google.com';
}
count--;
}, 1000);
}
function startStop() {
clearInterval(countdown);
}
The Updated Fiddle Example!

pause and continue using setInterval

what i want to achieve is when you click this href pause/continue the timer pauses and continues when pressed again.
<script>
$(document).ready(function () {
var counter = 10;
var id = setInterval(function() {
counter--;
if(counter > 0) {
var msg = 'You can continue ' + counter + ' seconds';
$('#notice').text(msg);
} else {
$('#notice').hide();
$('#download').show();
clearInterval(id);
}
}, 1000);
});
</script>
My HTML in relevance to the jQuery is here if you need.
Continue !!<p id="notice">
You can continue in 10 seconds</p>
Well, I would just have your pause event set a boolean, and then check that boolean before you decrement your counter:
pause/continue
and
var ispaused=false;
function setPause(){
ispaused=!ispaused;
}
and
$(document).ready(function () {
var counter = 10;
var id = setInterval(function() {
if(!ispaused){ ////the only new line I added from your example above
counter--;
if(counter > 0) {
var msg = 'You can continue ' + counter + ' seconds';
$('#notice').text(msg);
} else {
$('#notice').hide();
$('#download').show();
clearInterval(id);
}
}
}, 1000);
});
That should do it, right?

Categories

Resources