What can i do in this case? Setinterval within setinterval countdown timer - javascript

I need help or idea for use a countdown inside a setInterval.
heres my countdown timer on js (pretty obvious):
function startTimer(duration) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
document.getElementById('minuteDrag').innerText = minutes;
document.getElementById('secondDrag').innerText = seconds;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
When i call this function outside the second setinterval, that works pecfectly (as expected).
But when i tried to run this function in the code below, the function for time countdown gets bugged, i guess it's because the countdown timer is called within another setinterval.
Any ideas for a solution here? (i can't get out the "main setinterval").
var api = new Lolesports_API();
api.get_event_details('pt-BR', '105562529627228920')
.then(result_games => {
var game_id
result_games.event.match.games.forEach(game => game_id = game.id)
api.get_teams('pt-BR')
.then(result_teams =>{
var teams_dict = {}
result_teams.teams.forEach(team => {teams_dict[team.id] = team.code})
setInterval(function(){
api.get_window(game_id, get_lastest_date())
.then(result_window => {
var last_frame = result_window.frames[result_window.frames.length - 1];
var game_state = last_frame.gameState;
startTimer(60*5)
if (game_state == 'in_game') {
document.getElementById("gameState").style.backgroundColor = '#33cc33';
stopwatch_game.start();
} else if (game_state == 'paused') {
document.getElementById("gameState").style.backgroundColor = '#66a3ff';
stopwatch_game.pause();
} else {
document.getElementById("gameState").style.backgroundColor = '#ff8080';
stopwatch_game.pause();
}
//stopwatch_game.start();
})
}, 500)
})
})
PS: this is not the full code, i remove a large part in order not to pollute the question.

Right now you're starting a new CountDown Interval every half second.
Why not return the value from the setInterval in startTimer so that it can be stopped as necessary by the outer loop?
e.g.
startTimer = (duration) => {
let timer = duration, minutes, seconds;
return setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
document.getElementById('minuteDrag').innerText = minutes;
document.getElementById('secondDrag').innerText = seconds;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
Then in your main loop you can use clearInterval to stop the timer... or at least check if it exists:
let foo = undefined;
if (foo === undefined) {
foo = startTimer(60*5);
}

Related

How do you escape out of an alert box and resume flow of action? - Javascript

So i am writing a simple javascript timer, and at 30 seconds it prompts the user with an alert box if they would like to reset the count down or let it continue.
I am able to reset the timer however I get stuck when the user clicks cancel on the alert box.
I tried letting the timer just resume at its current time but that doesn't help as the alert box just keeps reappearing
I am still very new to javascript so I would like to stay using vanilla js till I get a deeper understanding of the fundamentals!
Any guidance would be greatly appreciated!
Heres my code:
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if(timer<30){
var message = confirm("Would you like to extend timer?");
if (message == true) {
timer = 60 * 1;
}
else{
timer = timer;
}
}
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
function resetTimer() {
timer = 60 * 1;
}
window.onload = function () {
var fiveMinutes = 60 * 1,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
just put if(timer==30) instead of if(timer<30) so that exactly at count of 30 units of time, you get asked once for confirmation at that instance (However be aware that until the confirmation is done, prompts will keep popping up every second). if you extend it, it will again wait till your timer goes down to 30 unit, else it will simply go down to 0 and break out.
function startTimer(duration, display) {
var timer = duration,
minutes,
seconds;
function timerFunc() {
timer -= 1;
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (timer == 30) {
var message = confirm("Would you like to extend timer?");
if (message == true) {
timer = 60;
} else return alert("Your timer has been stopped.")
}
setTimeout(timerFunc, 1000);
}
timerFunc();
}

Javascript start countdown and at the end call ajax

I am trying to start the Javascript countdown using following Javascript code. Here it's counting from 5 - 0.
Now I want when It's 0 then I will call an Ajax request (I know how to do it). But for now, I set it alert message that your session ends.
It continuously showing me the alert message But it's should be once!
Here is the JS code:
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if(timer !== 0 ) {
--timer;
} else if( timer == 0 ) {
alert('Your time has been completed.');
}
}, 1000);
}
window.onload = function () {
var seconds = 5,
display = document.querySelector('#time');
startTimer(seconds, display);
};
You need to assign the interval to a variable, so that you can then clear the interval after the final alert so that it doesn't run anymore:
function startTimer(duration, display) {
let timer = duration;
const interval = setInterval(function() {
let minutes = parseInt(timer / 60, 10)
let seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (timer !== 0) {
--timer;
} else if (timer == 0) {
alert('Your time has been completed.');
clearInterval(interval);
}
}, 1000);
}
window.onload = function() {
var seconds = 5,
display = document.querySelector('#time');
startTimer(seconds, display);
};
<div id="time"></div>
you need to make use of clearInterval() method as below
var myVar = setInterval(function(){ myTimer() }, 1000);
myTimer() {
if(conditionMet)
clearInterval(myVar);
}
or just for info you can make use of interval of react js
import { interval } from 'rxjs/observable/interval';
//emit value in sequence every 1 second
const source = interval(1000);
//output: 0,1,2,3,4,5....
const subscribe = source.subscribe(val => {
if(conditionmet)
source.unsubscribe();
console.log(val);
});
ES5
function startTimer(duration, display) {
var timer = duration;
var interval = setInterval(function() {
var minutes = parseInt(timer / 60, 10)
var seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (timer !== 0) {
--timer;
} else if (timer == 0) {
alert('Your time has been completed.');
clearInterval(interval);
}
}, 1000);
}
window.onload = function() {
var seconds = 5,
display = document.querySelector('#time');
startTimer(seconds, display);
};

countdown timer with number reduction after set point?

I've got a working countdown timer which starts at 30 minutes.
With only 3 minutes left (so after 27 minutes) I'd like the number 250 to decrease at random intervals from 3 minutes left down to the end of the countdown.
Any ideas?
https://codepen.io/anon/pen/bWoGrb
// Stopwatch
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
window.onload = function () {
var thirtyMinutes = 60 * 30,
display = document.querySelector('#stopwatch');
startTimer(thirtyMinutes, display);
};
<div id='stopwatch'></div>
Maybe use something like this (I hope I clearly understood the question):
Just using a if/else within the condition something to say: Go normal when more than 60*3, and when under 60*3 seconds rest, there is chance to do nothing
// Stopwatch
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
if(timer > 60*3 || Math.random() < 0.25) {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
}
} else {
/* do not reduce the timer to wait 1 interval more */
/* or maybe do like `timer -= Math.random()` if you want to reduce it faster */
}
}, 1000);
}
window.onload = function () {
var thirtyMinutes = 60 * /*30*/ 4, // just set to 4 to see faster
display = document.querySelector('#stopwatch');
startTimer(thirtyMinutes, display);
};
<div id='stopwatch'></div>

Reducing Repetitive Javascript Functions

Related to this previous Question: How to stop a Javascript Timer after the second countdown?
I figured out a way for my Pomodoro clock to function properly, but my code is pretty repetitive. I couldn't figure out a way to not recreate the same (or very similar function) without the second break timer continuously running. Any ideas?
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
var countdown = setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
//minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
$(".startClock").click(function () {
clearInterval(countdown);
});
if (--timer < 0) {
clearInterval(countdown);
breakClock();
}
}, 500);
}
function breakTimer(duration, display) {
var timer = duration, minutes, seconds;
var countdown = setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
//minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
$(".startClock").click(function () {
clearInterval(countdown);
});
if (--timer < 0) {
clearInterval(countdown);
}
}, 500);
$("body").css("background-color", "#E13F86");
$("#title").text(function(i, text){
return text === 'Breaktime' ? 'Productive Countdown' : 'Breaktime'
});
}
var display = document.querySelector('#time');
function startClock() {
var twentyfiveMinutes = 60 * .25;
startTimer(twentyfiveMinutes, display);
}
function breakClock() {
var fiveMinutes = 60 * .05;
breakTimer(fiveMinutes, display);
}
$(".startClock").on("click", function() {
startClock();
});
Here's my codepen as well: http://codepen.io/cenjennifer/pen/pjzBVy?editors=101
Your code is fine. jfriend00 is right, this code does belong on the code review page.
But since I'm here, I will give some feedback. Make an object (using function(){}), and put all of your functions inside of the object.
Instead of recreating all your variables in each function, make them properties inside of the object, so that they are accessible to all of the functions, and so that you don't need to keep recreating them. (Variables like timer, hour, minutes, should be moved as object properties).
Also, don't use global variables, they can interfere with libraries you may find to be useful later on. You should namespace, so that the code is more organized, and does not get overwritten by other globals.
The easy way to reuse the function, is to share the timer returned by setInterval and provide a callback in the startTimer function (used for both start and break). The callback, if provided, takes care of the code to run after the timer finishes. Therefore the specific code can be omitted from startTimer. Also since the timer is shared, no matter when started, the original loop can be stopped when called again (the button is clicked again), so that too can be omitted from the startTimer function, thus making it ready for reusability. The whole would look something like:
var currentcountdown;
var display = document.querySelector('#time');
function startTimer(duration, callback) {
var timer = parseInt(duration), minutes, seconds;
clearInterval(currentcountdown);
currentcountdown = setInterval(function () {
minutes = Math.floor(timer / 60);
seconds = Math.floor(timer % 60);
//minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
clearInterval(currentcountdown);
if(callback)
callback();
}
}, 500);
}
function startClock() {
$("body").css("background-color", "black");
$("#title").text('Productive Countdown');
var twentyfiveMinutes = 60 * .25;
startTimer(twentyfiveMinutes, breakClock);
}
function breakClock() {
$("body").css("background-color", "#E13F86");
$("#title").text('Breaktime');
var fiveMinutes = 60 * .05;
startTimer(fiveMinutes);
}
$(".startClock").on("click", function() {
startClock();
});
As mentioned in the other post, synthetic sugar would be to put all values into objects (such as duration/background/title) and optionally put the timer and its variables (display/timer) into an object, but for straight forward re-usability of the function the above should provide a good start.

Call timer function for several times in ajax success event

Here is my current code for timer:
function startTimer() {
var duration = 60*3;
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
$('.minutes').html(minutes);
$('.seconds').html(seconds);
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
This function is working, let say I got an ajax to call this function :
$.ajax({
url : '/sample_url/',
success : function (data)
{
startTimer();
}
});
Here is my question, I run this startTimer function is ok, however if I used ajax to call it for several times, the timer not countdown at 3 minutes...

Categories

Resources