Calling functions one from the other and vice versa - javascript

I have two timers with two boolean variables and two functions. The first timer is triggered by a click that put true one of the booleans; once the timer reach some conditions this timer is off setting false the boolean and another timer is triggered setting true the second boolean and calling the second timer.
Same once the second timer reach some conditions, the timer is off setting the second boolean false and I try to trigger the first timer setting the first boolean true and calling the first timer, but it dosn't work.
I cannot call the function that is declared underneath the funcion where I do the call.
My code in JavaScript is:
var active=false;
var activeBreak=false;
...
function breakDown(){
if(activeBreak){
...
if(some conditions){
active=true;
activeBreak=false;
countDown();// **This call doesn't work.Black in jsbin**
}
}
}
function countDown(){
if(active){
...
if(someConditions){
active=false;
activeBreak=true;
breakDown();// *This call works. Blue in jsbin*
}
}
}
...
$("#circle").click(function(){
active=true;
countDown(); // *This call works*/
});

Try
$(document).ready(function(){
/* Global variables */
var state = 'STOPPED';
var timeSession = 1;
var timeBreak = 1;
var timeout = 0;
function resetTimer(time) {
timeout = (new Date()).getTime() + (time*60*1000);
}
function changeState() {
if (state === 'SESSION') {
state = 'BREAK';
resetTimer(timeBreak);
} else if (state === 'BREAK' || state === 'STOPPED') {
state = 'SESSION';
resetTimer(timeSession);
}
$('#text').text(state);
}
/* Function for the countdown ****************************/
function countDown (){
if (state !== 'STOPPED') {
var time = (new Date()).getTime();
if (timeout <= time) {
changeState();
return;
}
var s = Math.floor((timeout - time) / 1000);
var m = Math.floor(s / 60);
s = s - m*60;
$('#timer').text(""+((timeout - time) / 1000)+" "+timeout+" "+m+":"+("0"+s).substr(-2));
}
setTimeout(countDown, 1000);
}
/*****Click Break ********************/
$("#breakMinus").click(function(){
if (timeBreak > 1) {
--timeBreak;
}
$("#breakContent").html(timeBreak);
});
$("#breakPlus").click(function(){
++timeBreak;
$("#breakContent").html(timeBreak);
});
/******Click Session Length****************/
$("#seMinus").click(function(){
if (timeSession > 1) {
--timeSession;
}
$("#seContent").html(timeSession);
});
$("#sePlus").click(function(){
++timeSession;
$("#seContent").html(timeSession);
});
/***********Click circle****************/
$("#circle").click(changeState);
setTimeout(countDown, 1000);
$('#text').text(state);
});

Related

Set up a pause/resume-able timer in javascript

Is there a way to create a "timer"(or stopwatch) class, that the timers created using this class can be paused and resumed on triggering an event, e.g. clicking a button?
I tried to create the class and create timer objects using it, but the timer cannot be paused once it starts.
My attempt on creating this class:
class countdown {
constructor(min, sec) {
this.mins = min;
this.secs = sec;
this.handler = 0;
}
static setTimer(x,minfield,secfield) {
this.handler = setTimeout(() => {
if (x.mins == 0 && x.secs == 0) {
clearTimeout();
} else {
if (x.secs == 0) {
x.mins -= 1;
x.secs = 59;
} else {
x.secs -= 1;
}
}
this.updateTimer(x,minfield,secfield);
this.setTimer(x,minfield,secfield)
}, 1000)
}
static updateTimer(x,minfield, secfield){
document.getElementById(minfield).innerHTML = x.mins;
document.getElementById(secfield).innerHTML = x.secs;
}
static stopTimer(x,minfield,secfield) {
// document.getElementById(minfield).innerHTML = x.mins;
// document.getElementById(secfield).innerHTML = x.secs;
clearTimeout(x.handler);
}
}
Usage:
let countdown1 = new countdown(15,0);
let countdown_act = false;
document.getElementById('button').addEventListener( 'click', () => {
if (!countdown_act) {
countdown.setTimer(countdown1, 'ctdwn-mins', 'ctdwn-secs');
countdown_act = true;
} else {
countdown.stopTimer(countdown1, 'ctdwn-mins', 'ctdwn-secs');
countdown_act = false;
}
console.log(countdown_act);
}
)
The countdown_act flag is used for indicating the state of the timer.
There's no need for any of your methods to be static. Also, it's much simpler and easier to use if you just record seconds and then calculate minutes when you need the output. As a standard, capitalize the name of classes. Finally, you're probably looking for setInterval, not timeout.
Think of a real-world timer. You can set it, start it, pause it, and stop it. Stopping a timer is really just restarting it and pausing it, and it's set upon creation, so let's make a Timer with start, pause, set and stop or reset. This still behaves the same way as yours in the background by using a 1s timeout, but it's a lot cleaner and easier for someone reading your code to understand:
class Timer {
constructor(seconds, callback) {
this.originalTime = seconds;
this.remainingTime = seconds;
this.timeout = null;
this.callback = callback; // This is what the timer does when it ends
}
start() {
this.timeout = setInterval(() => {
this.remainingTime -= 1; // Remove a second from the timer
if(this.remainingTime === 0) {
this.callback(); // Run the callback function
this.stop(); // Stop the timer to prevent it from counting into the negatives
}
}, 1000);
}
pause() {
clearInterval(this.timeout);
}
stop() {
this.pause();
this.remainingTime = this.originalTime; // Reset the time
}
setTime(seconds) {
this.originalTime = seconds; // Set a new time
this.stop(); // Have to restart the timer to account for the new time
}
get remaining() {
return {
seconds: this.remainingTime % 60,
minutes: Math.floor(this.remainingTime / 60)
}
}
}

Stopping a function from running

I have 3 sequential divs to display on a page, the page loads showing div 1, by going onto the 2nd it starts a timer, when that timer runs out it goes back to the first div. Navigating through to the next div should start the timer again. The timer function works OK on the first page but on the second page when it is called it is already running from the previous div and therefore ticks the time down twice as fast, and on the last div 3 times.
How can I get it to stop the currently running function then restart it?
Thanks,
$scope.timeLeft = 0;
var timeoutRunner = function (timerLength) {
$scope.timeLeft = timerLength;
var run = function () {
if ($scope.timeLeft >= 1) {
console.log($scope.timeLeft);
$scope.timeLeft--
$timeout(run, 1000);
} else if ($scope.timeLeft == 0){
$scope.endTransaction();
}
}
run();
}
timeoutRunner(5);
You need to add some logic that calls $timeout.cancel(timeoutRunner);.
Not sure where you want to cancel your timeout exactly (view change? when you end the transaction?) But here is how you would do it:
$scope.timeLeft = 0;
var timeoutPromise = false;
var timeoutRunner = function (timerLength) {
$scope.timeLeft = timerLength;
var run = function () {
if ($scope.timeLeft >= 1) {
console.log($scope.timeLeft);
$scope.timeLeft--
timeoutPromise = $timeout(run, 1000);
} else if ($scope.timeLeft == 0){
$scope.endTransaction();
$timeout.cancel(timeoutPromise);
}
}
run();
}
timeoutRunner(5);
Each time I called the function it created a new instance of it and I was unable to stop it on demand so I found a way to say which instance I want running:
$scope.timeLeft = 0;
var instanceRunning = 0;
var timeoutRunner = function (timerLength, instance) {
$scope.timeLeft = timerLength;
instanceRunning = instance;
var run = function () {
if (instanceRunning == instance){
if ($scope.timeLeft < 7 && $scope.timeLeft > 0){
$('#timer-container').show();
} else {
$('#timer-container').hide();
}
if ($scope.timeLeft >= 1) {
console.log($scope.timeLeft);
$scope.timeLeft--
$timeout(run, 1000);
} else if ($scope.timeLeft == 0){
$scope.endTransaction();
}
}
}
run();
}
timeoutRunner(20, 1);
timeoutRunner(20, 2);
timeoutRunner(20, 3);

Stopping timer not working:

I have THIS timer in my project.
When it runs out, it shows a Time Up screen, which works fine.
But when the player is Game Over, i show the Game Over screen, but the timer keeps running and when it hits 00:00 then it switches to the Time Up screen.
How can i make this timer stop counting down and set to 00:00 again?
I tried adding a function like this:
CountDownTimer.prototype.stop = function() {
diff = 0;
this.running = false;
};
I also tried to change the innerHTML but its obvious that its just changing the numbers without stopping the timer and after a second it will show the count down again... I don't know what to call.
//Crazy Timer function start
function CountDownTimer(duration, granularity) {
this.duration = duration;
this.granularity = granularity || 1000;
this.tickFtns = [];
this.running = false;
}
CountDownTimer.prototype.start = function() {
if (this.running) {
return;
}
this.running = true;
var start = Date.now(),
that = this,
diff, obj;
(function timer() {
diff = that.duration - (((Date.now() - start) / 1000) | 0);
if (diff > 0) {
setTimeout(timer, that.granularity);
} else {
diff = 0;
that.running = false;
}
obj = CountDownTimer.parse(diff);
that.tickFtns.forEach(function(ftn) {
ftn.call(this, obj.minutes, obj.seconds);
}, that);
}());
};
CountDownTimer.prototype.onTick = function(ftn) {
if (typeof ftn === 'function') {
this.tickFtns.push(ftn);
}
return this;
};
CountDownTimer.prototype.expired = function() {
return !this.running;
};
CountDownTimer.parse = function(seconds) {
return {
'minutes': (seconds / 60) | 0,
'seconds': (seconds % 60) | 0
};
};
window.onload = function () {
var display = document.querySelector('#countDown'),
timer = new CountDownTimer(timerValue),
timeObj = CountDownTimer.parse(timerValue);
format(timeObj.minutes, timeObj.seconds);
timer.onTick(format).onTick(checkTime);
document.querySelector('#startBtn').addEventListener('click', function () {
timer.start();
});
function format(minutes, seconds) {
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ':' + seconds;
}
function checkTime(){
if(this.expired()) {
timeUp();
document.querySelector('#startBtn').addEventListener('click', function () {
timer.start();
});
}
}
};
Instead of recursively calling setTimeout, try setInterval instead. You could then store a reference to the timer:
this.timer = setInterval(functionToRunAtInterval, this.granularity);
and kill it when the game finishes::
clearInterval(this.timer)
(see MDN's docs for more info on setInterval)
It's been a while and I'm not sure if you've figured it out but check out the fiddle below:
https://jsfiddle.net/f8rh3u85/1/
// until running is set to false the timer will keep running
if (that.running) {
if (diff > 0) {
setTimeout(timer, that.granularity);
} else {
diff = 0;
that.running = false;
}
obj = CountDownTimer.parse(diff);
that.tickFtns.forEach(function(ftn) {
ftn.call(this, obj.minutes, obj.seconds);
}, that);
}
I've added a button that causes running to be set to false which stops the timer.
Button:
<button id="stop">Game Over</button>
Code:
$( "#stop" ).click(function() {
timer.running = false;
});
So that should hopefully get you to where you need to be.
Similar to Tom Jenkins' answer, you need to cancel the next tick by avoiding the diff > 0 branch of your if statement. You could keep your code as it stands and use your suggested stop method, however, you'd need to change your logic around handling ticks to check that both running === true and a new param gameOver === false.
Ultimately, I think your problem is that no matter whether the timer is running or not, you'll always execute this code on a tick:
obj = CountDownTimer.parse(diff);
that.tickFtns.forEach(function(ftn) {
ftn.call(this, obj.minutes, obj.seconds);
}, that);
If you have a game over state, you probably don't want to call the provided callbacks, so add some conditional check in there.

clearInterval() not working?

function myFunction(interval) {
var intervalID = window.setInterval(function () {
getdetails();
$('.View').load('alert.php').fadeIn("slow");
}, 3000);
if (interval == 1) {
window.clearInterval(intervalID);
}
}
when I call myFunction with argument 1 then clearInterval() not clear the setInterval().I want setInterval() stop its excution when I call myFunction with argument 1.
The problem is that you are creating a new timer everytime you call the function. Modify it like:
var intervalID = 0;
function myFunction(interval){
if(interval == 1) {
if(intervalID != 0) {
window.clearInterval(intervalID);
intervalID = 0;
}
}
else if(intervalID == 0) { // create only if not existing
intervalID = window.setInterval(function () {
...
});
}
}
Now, the firts time you call it, it will create the timer. Afterwards when you call it with 1 as the argument, it will clear the timer.

Not able to kill previous counter when countdown is placed in a loop

I am using a simple countdown as such below which is working fine except when it is placed in the loop. During looping both previous and new counter remains working .I want to kill the previous counter and start with a new, which i am not able to achieve. Can anybody help on this please
function triggerEvery60Sec(){
var myCounter = new Countdown({
seconds:5, // number of seconds to count down
onUpdateStatus: function(sec){console.log(sec);}, // callback for each second
onCounterEnd: function(){ alert('counter ended!');} // final action
});
myCounter.start();
}
function Countdown(options) {
var timer,
instance = this,
seconds = options.seconds || 10,
updateStatus = options.onUpdateStatus || function () {},
counterEnd = options.onCounterEnd || function () {};
function decrementCounter() {
updateStatus(seconds);
if (seconds === 0) {
counterEnd();
instance.stop();
}
seconds--;
}
this.start = function () {
clearInterval(timer);
timer = 0;
seconds = options.seconds;
timer = setInterval(decrementCounter, 1000);
};
this.stop = function () {
clearInterval(timer);
};
}
Instead of declare your variable in the loop, maybe should you declare it before, and manipulate it during your loop.
var myCounter = null;
function triggerEvery60Sec(){
myCounter = new Countdown({
seconds:5, // number of seconds to count down
onUpdateStatus: function(sec){console.log(sec);}, // callback for each second
onCounterEnd: function(){ alert('counter ended!');} // final action
});
myCounter.start();
}

Categories

Resources