Reset Counter OnClick - javascript

I have some code I am using to countdown from 15 after 15 secs passes it echoes "times over". The problem is if someone clicks twice there will be two counters in the same Div. I need the counter to reset if someone clicks on the button again.
function startCountDown(i, p, f) {
// store parameters
var pause = p;
var fn = f;
// make reference to div
var countDownObj = document.getElementById("countDown");
if (countDownObj == null) {
// error
alert("div not found, check your id");
// bail
return;
}
countDownObj.count = function (i) {
// write out count
countDownObj.innerHTML = i;
if (i == 0) {
// execute function
fn();
// stop
return;
}
setTimeout(function () {
// repeat
countDownObj.count(i - 1);
},
pause);
}
// set it going
countDownObj.count(i);
}
function myFunction() {
alert("Time Over");
}
HTML:
<div id="TimerTitle">Timer</div>
<span id="countDown"></span>
<button onclick="startCountDown(15, 1000, myFunction);">
Start Time
</button>

Set the timeout as a global variable like so:
timer = setTimeout(function(){countDownObj.count(i - 1);},pause);
At the beginning of the function clear the timeout
clearTimeout(timer)
Code:
var timer;
function startCountDown(i, p, f) {
// store parameters
if(timer){clearTimeout(timer)}
var pause = p;
var fn = f;
// make reference to div
var countDownObj = document.getElementById("countDown");
if (countDownObj == null) {
// error
alert("div not found, check your id");
// bail
return;
}
countDownObj.count = function (i) {
// write out count
countDownObj.innerHTML = i;
if (i == 0) {
// execute function
fn();
// stop
return;
}
timer = setTimeout(function(){countDownObj.count(i - 1);},pause);
}
// set it going
countDownObj.count(i);
}
function myFunction() {
alert("Time Over");
}

setTimeout returns an id to the timer that can be used with window.clearTimeout. The simplest solution would be to create a global timerId
var timerId;
...
function startCountDown(i, p, f) {
...
if (timerId) { window.clearTimeout(timerId); }
timerId = window.setTimeout(...);
https://developer.mozilla.org/en-US/docs/Web/API/Window.setTimeout

Related

function not working when i click button?

when i click my button, a timer is supposed to display a countdown timer. But the button does not work.
let timerCounter = document.getElementById("timer-counter");
let timer;
let timerCount;
function startTimer() {
timer = setInterval(function() {
timerCount--;
timerElement.textContent = "Time; " + timerCount;
if (timerCount === 0) {
clearInterval(timer);
}
});
}
startButton.addEventListener("click", startTimer);
This is what I found so far:
You are decrementing the timerCount, need to specify the initial value for it to work.
You're using timerElement instead of timerCounter that you've declared.
You must pass the second args to the setInterval which is delay.
const timerCounter = document.getElementById('timer-counter');
const startButton = document.getElementById('start-button');
let timer;
let timerCount = 30;
startButton.addEventListener('click', startTimer);
function startTimer() {
timer = setInterval(function () {
timerCount--;
timerCounter.textContent = 'Time; ' + timerCount;
if (timerCount === 0) {
clearInterval(timer);
}
}, 1000);
}
<div id="timer-counter"></div>
<button id="start-button">Start</button>
Here's a slightly different approach that avoids some of the problems with global variables. The function the listener calls initialises the count, and then returns a new function (a closure) that is called when the button is clicked. It also uses setTimeout which I find more easy to understand.
// Cache your elements
const counter = document.querySelector('#counter');
const startButton = document.querySelector('button');
// Initialise your count variable
function startTimer(count = 30) {
// Return a function that is called from
// the listener
return function loop () {
// Disabled the button once it's been clicked
if(!startButton.disabled) startButton.disabled = true;
counter.textContent = `Time: ${count}`;
if (count > 0) {
setTimeout(loop, 500, --count);
}
}
loop();
}
// Call startTimer to initialise the count, and return
// a new function that is used as the listener
startButton.addEventListener('click', startTimer(), false);
<div id="counter"></div>
<button>Start</button>
I'm sure this could be improved.
In this example we don't go below 0.
We don't allow timeout collisions ( timeouts don't stack causing weird counting speeds ).
We can reset to the original number when on 0.
const c = document.getElementById('timer-counter')
const b = document.getElementById('start-button')
let timer = false
let timerCount = 30
b.addEventListener('click', start)
function decrement() {
if(timerCount < 0) {
timerCount = 30
timer = false
return
}
c.innerText = `Count: ${timerCount}`
timerCount--
timer = setTimeout(decrement, 200)
}
function start() {
if(timer) return
decrement()
}
<div id="timer-counter"></div>
<button id="start-button">Start</button>

Javascript Memory

I was wondering why my program crashes after its made its first match....any ideas would be greatly appreciated. Below is the code snippet. Thanks for the input!
var clicks = 0; //counts how may picks have been made in each turn
var firstchoice; //stores index of first card selected
var secondchoice; //stores index of second card selected
var match = 0; //counts matches made
var backcard = "deck.jpg"; //shows back of card when turned over
var faces = []; //array to store card images
faces[0] = 'pic1.jpg';
faces[1] = 'pic2.jpg';
faces[2] = 'pic3.jpg';
faces[3] = 'pic3.jpg';
faces[4] = 'pic2.jpg';
faces[5] = 'pic1.jpg';
function choose(card) {
if (clicks === 2) {
return;
}
if (clicks === 0) {
firstchoice = card;
document.images[card].src = faces[card];
clicks = 1;
} else {
clicks = 2;
secondchoice = card;
document.images[card].src = faces[card];
timer = setInterval("check()", 1000);
}
}
/* Check to see if a match is made */
function check() {
clearInterval(timer); //stop timer
if (faces[secondchoice] === faces[firstchoice]) {
match++;
document.getElementById("matches").innerHTML = match;
} else {
document.images[firstchoice].src = backcard;
document.images[secondchoice].src = backcard;
clicks = 0;
return;
}
}
The first parameter of setInterval needs to be a function not a string pretending to be a function. So you would want this:
timer = setInterval(function() { check(); }, 1000);
Of course, you can simplify:
timer = setInterval(check, 1000);
Not sure why you're using setInterval() here. You could more easily just do:
timer = setTimeout(check, 1000);
The advantage is there is no interval to clear in the check() function.
The other issue is that you are not resetting your 'clicks' counter to 0 when there is a match.
You want this:
function check() {
clearInterval(timer); //stop timer
if (faces[secondchoice] === faces[firstchoice]) {
match++;
document.getElementById("matches").innerHTML = match;
} else {
document.images[firstchoice].src = backcard;
document.images[secondchoice].src = backcard;
}
clicks = 0;
}
I think you have to declare you timer function globally. Its only defined in the scope of the first function, so in the second when you try to clear it nothing happens:
var timer = ''; //Declare timer up here first!
function choose(card) { ... }
function check() { ... }

SetInterval doesn't same when called again?

I'm making a simple program which increases a number incrementally for every 0.5 second. When I click start it works perfectly. But when I click restart, the increments go fine, but they don't increment every 0.5 sec and go pretty fast, and this happens when I am calling the same function? JS fiddle link below.
function runFunc(){
declare a variable interval outside function
var myInterval = null;
check if an interval is already running if yes clear it in order to avoid multiple interval running the same function which makes the interval became looks faster than the first time it's called
if (myInterval != null) {
clearInterval(myInterval);
}
also this is not correct
clearInterval(varName);
the parameter should be an interval which is like this
clearInterval(myInterval);
so your javascript code would be like this
var myInterval = null;
function runFunc(){
$('#counter').val(zero);
var varName = function(){
var number = Number($('#number').val());
var counter = Number($('#counter').val());
if(counter < number) {
counter++;
console.log(counter);
$('#counter').val(counter);
} else {
clearInterval(myInterval);
}
};
//check if an interval is already running if yes clear it
if (myInterval != null) {
clearInterval(myInterval);
}
myInterval = setInterval(varName, 500);
};
show.click(runFunc);
reset.click(function(){
$('#number').val(zero);
$('#counter').val(zero);
});
restart.click(runFunc);
u have to Declare a Variable for setInterval like "setIntervalID"
so stop it clearInterval("setIntervalID");
JSFIDDLE
var initialNumber = 10;
var zero = 0;
$('#number').val(initialNumber);
$('#counter').val(zero);
var show = $('#show');
var reset = $('#reset');
var restart = $('#restart');
var setIntervalID;
// console.log('initial value of number is ' + number);
// console.log(typeof number);
// console.log('initial value of counter is ' + counter);
var varName = function(){
var number = Number($('#number').val());
var counter = Number($('#counter').val());
if(counter < number) {
counter++;
console.log(counter);
$('#counter').val(counter);
}
}
function runFunc(){
$('#counter').val(zero);
setIntervalID = setInterval(varName, 500);
};
function stopFunc(){
clearInterval(setIntervalID);
};
function restartGO(){
stopFunc();
runFunc();
}
show.click(runFunc);
restart.click(restartGO);
reset.click(function(){
$('#number').val(zero);
$('#counter').val(zero);
});

Javascript function not being able to call when sessionStorage value is compared

I am currently creating a flash gallery and every time a new button is pressed to see a new flash I would like to see the page reload to display a new ad. I've troubleshooted the problem with console.logs and have identified that the the sessionStorage variables are being set correctly but when it comes time to call the back/rand/next() functions it just stops in its tracks. Any tips will be of great value.
(Edit) It gets to console.log('Rand button ses received!');
CODE
var flashcon, test, temp;
var back, rand, next;
back = document.getElementById('back');
rand = document.getElementById('rand');
next = document.getElementById('next');
flashcon = document.getElementById('flashcon');
function init() {
if (sessionStorage.getItem('ref') == 1) {
console.log('Back button ses received!');
back();
} else if (sessionStorage.getItem('ref') == 2) {
console.log('Rand button ses received!');
rand();
} else if (sessionStorage.getItem('ref') == 3) {
console.log('Next button ses received!');
next();
} else {
console.log('First time or a reset');
}
// Scripts for the buttons
back.onclick = function () {
console.log('Back button pressed');
sessionStorage.setItem('ref', 1);
location.reload();
};
rand.onclick = function () {
console.log('Rand button pressed');
sessionStorage.setItem('ref', 2);
location.reload();
};
next.onclick = function () {
console.log('Next button pressed');
sessionStorage.setItem('ref', 3);
location.reload();
};
}
// What switches the flashs
function back() {
console.log('Back function');
sessionStorage.clear();
if (c == 0) {
c = paths.length;
}
c--;
displayFiles();
download();
}
function rand() {
console.log('Rand function');
sessionStorage.clear();
if (c == paths.length - 1) {
c = -1;
}
c++;
displayFiles();
download();
}
function next() {
console.log('Next function');
sessionStorage.clear();
temp = c;
while (c == temp) {
c = Math.floor(Math.random() * paths.length);
}
displayFiles();
download();
}
You have variables and functions over-riding each others' names.
back, next, rand are all function statements which get hoisted above the ... = document.getElementById('...') for the corresponding variable names.
Change the function names or change the element object names and then try again.
So basically turn this:
var back, rand, next;
back = document.getElementById('back');
rand = document.getElementById('rand');
next = document.getElementById('next');
into this:
var $back, $rand, $next;
$back = document.getElementById('back');
$rand = document.getElementById('rand');
$next = document.getElementById('next');
and of course edit the matching places following in the code so they point to the right variable.

clearInterval does not work

I'm trying to create a simple countdown timer. It counts down from the number entered.
However, I'm trying to clear the interval when the counter gets to 0. At the moment it seems to acknowledge the if statement, but not clearInterval().
http://jsfiddle.net/tmyie/cf3Hd/
$('.click').click(function () {
$('input').empty();
var rawAmount = $('input').val();
var cleanAmount = parseInt(rawAmount) + 1;
var timer = function () {
cleanAmount--;
if (cleanAmount == 0) {
clearInterval(timer);
}
$('p').text(cleanAmount);
};
setInterval(timer, 500);
})
You're not saving the return value of the call to setInterval, which is the value that needs to be passed to clearInterval. Passing the timer handler does no good.
var timer, timerHandler = function () {
cleanAmount--;
if (cleanAmount == 0) {
clearInterval(timer);
}
$('p').text(cleanAmount);
};
timer = setInterval(timerHandler, 500);

Categories