Timer is not getting reset using clearInterval() - javascript

This is my Timer function
var myTimer = setInterval(function () {
var d = new Date();
var seconds = d.getMinutes() * 60 + d.getSeconds();
var fiveMin = 60 * 5;
var timeleft = fiveMin - seconds % fiveMin;
var result = parseInt(timeleft / 60) + ':' + timeleft % 60;
//console.log(result);
var timerObj = {
timer : result
}
$scope.timerArray = timerObj;
$scope.$apply();
if (timeleft === 1) {
$scope.statusDetails = [];
$scope.timeDetails();
$scope.get_dbStatus();
}
}, 1000);
This function will reset the above timer when I click a button.
$scope.refreshStatusList = function(){
$scope.hide = true;
$scope.$emit('LOAD');
clearInterval(myTimer);
$scope.statusDetails = [];
$scope.timeDetails();
$scope.get_dbStatus();
};
This is my refresh button in html page upon clicking it the timer must get reset.
<div class="col-lg-2">
<a href="#" title="Refresh" ng-click="refreshStatusList();">
<i class="fa fa-refresh fa-lg"></i>
</a>
</div>

Since, you are using angularjs, You should use $interval directive, which will internally call $scope.apply()
Usage
$scope.intervalPromise = $interval(function () {
//Your code
}, 1000);
To clear interval
$interval.cancel($scope.intervalPromise);

Try using this
$scope.apply();

Related

stop interval inside a function

I have this script that runs a soccer game clock,
when I click the start button everything is working properly
but I can't stop the clock.
var count;
function gameClock() {
var minutesLabel = document.getElementById("minutes");
var secondsLabel = document.getElementById("seconds");
var totalSeconds = 0;
var count = setInterval(function() {
setTime()
}, 1000);
function setTime() {
++totalSeconds;
secondsLabel.innerHTML = pad(totalSeconds % 60);
minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));
}
function pad(val) {
var valString = val + "";
if (valString.length < 2) {
return "0" + valString;
} else {
return valString;
}
}
}
//Start Stop Game Clock
$(document).on('click', '#f_start', function() {
$("#half_name").text('FIRST HALF');
gameClock();
// localStorage.setItem('first_half_click', getTime());
// localStorage.setItem('half', 1);
})
$(document).on('click', '#f_stop', function() {
clearInterval(count);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="col-2">
<button class="btn btn-success" id="f_start"> START</button>
</div>
<div class="col-2">
<button class="btn btn-danger" id="f_stop"> STOP</button>
</div>
You are redeclaring the count global variable inside the gameClock method which means it's scope is only in that function. change the assignment to use the global count variable instead of the useless local variable.
var count = setInterval(function() {
setTime()
}, 1000);
//to
count = setInterval(function() {
setTime()
}, 1000);

How to make a countdown with input field with how many minutes the countdown must go?

I have made a countdown but now I want to make a input field with how many minutes the countdown should countdown from. What I have is a pretty basic countdown but what I don't have is that a user puts the amount of minutes into the input field, click the button, and it counts down the minutes. And I hope someone can help me with this.
This is what I got so far:
(()=> {
let countdownEnded = false;
start(3600); // seconds
})();
function start(inputTime){
let startTime = Date.now();
intervalSeconds = setInterval(() => {
let currentTime = Date.now() - startTime;
if(inputTime < 1) {
stop();
} else {
updateDisplay(inputTime, currentTime);
updateMillis();
}
}, 1000);
}
function stop(){
let countDivElement = document.getElementById("countdown"); /*** Updated***/
countDivElement.innerHTML = 'countdown done';
countdownEnded = true; /*** Updated***/
}
function updateDisplay(seconds, currentTime){
let timeIncrement = Math.floor(currentTime / 1000);
updateTime(seconds - timeIncrement);
}
/**
* #method - updatesecondsond
* #summary - This updates the timer every seconds
*/
function updateTime(seconds) {
let countDivElement = document.getElementById("timer");
let minutes = Math.floor(seconds / 60);
let remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = '0' + remainingSeconds;
}
if (minutes < 10) {
minutes = '0' + minutes;
}
if (seconds > 0) {
seconds = seconds - 1;
} else {
clearInterval(intervalSeconds);
countdownEnded = true;
countDivElement.innerHTML = 'countdown done';
return null;
}
countDivElement.innerHTML = minutes + ":" + remainingSeconds + ":" ;
};
function updateMillis() {
let countMillsElement = document.getElementById('millis');
let counterMillis = 99;
let millis;
let intervalMillis = setInterval(()=> {
if(counterMillis === 1) {
counterMillis = 99;
} else {
millis = counterMillis < 10 ? '0' + counterMillis : counterMillis;
};
countMillsElement.innerHTML = millis;
counterMillis --;
}, 10);
if(countdownEnded) {
stop(); /*** Updated***/
return clearInterval(intervalMillis);
}
};
<div class="clock" id="model3">
<div id="countdown"> <!-- Updated -->
<span id="timer"></span><span id="millis"></span>
</div>
</div>
<input id="minutes" placeholder="0:00"/>
I think this may help you.
Change the following
<input id="minutes" placeholder="00"/> <button onclick="startTimer()">Start</button>
And in javascript add a new function
function startTimer(){
var x=document.getElementById("minutes").value * 60; //To Change into Seconds
start(x);
}
And remove the start function
Just add a button with click event that takes input value and triggers your 'start' function with that value as parameter. Something like this:
document.getElementById("startBtn").addEventListener("click", startTimer);
function startTimer() {
var numberOfMinutes = Number(document.getElementById("minutes").value) * 60;
start(numberOfMinutes);
}
And remove 'start' function call from the window load to prevent the timer to start immidiately.
Result is something like this:
https://jsfiddle.net/scarabs/6patc9mo/1/

Javascript Countdown Seconds Skip As I Add More Than One Timer Inside Page

I have added a javascript countdown timer to my page but i would like to add more than one timer inside my page. when i add more timers the seconds counter start to skip.
here's my markup code
<div class="fa countdown-timer" style="font-size: x-large">
<span class="fa hrRemaining"></span>:<span class="minRemaining"></span>:<span class="secRemaining"></span>
</div>
<div class="fa countdown-timer" style="font-size: x-large">
<span class="fa hrRemaining"></span>:<span class="minRemaining"></span>:<span class="secRemaining"></span>
</div>
<div class="fa countdown-timer" style="font-size: x-large">
<span class="fa hrRemaining"></span>:<span class="minRemaining"></span>:<span class="secRemaining"></span>
</div>
here's my javascrpit timer
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
var remSeconds = Math.floor(#timeRemaining);
var secondsCounter = Math.floor(remSeconds % 60);
var minutesCounter = Math.floor((remSeconds / 60) % 60);
var hoursCounter = Math.floor((remSeconds / 3600));
function formatNumber(number) {
if (number < 10)
return '0' + number;
else
return '' + number;
}
function startTimers() {
var $timers = $('.countdown-timer');
// See https://api.jquery.com/each/
$timers.each(function() {
// `this` is the current `.countdown-timer` being iterated by jQuery.each()
var $timer = $(this);
var $seconds = $timer.find('.secRemaining');
var $minutes = $timer.find('.minRemaining');
var $hours = $timer.find('.hrRemaining');
$seconds.text(formatNumber(secondsCounter));
$minutes.text(formatNumber(minutesCounter));
$hours.text(formatNumber(hoursCounter));
var _tick = setInterval(function() {
if ((remSeconds) > 0) {
if (hoursCounter > 0) {
if (minutesCounter == 0) {
minutesCounter = 60;
hoursCounter = hoursCounter - 1;
}
}
if (secondsCounter == 0) {
secondsCounter = 60;
minutesCounter = minutesCounter - 1;
}
secondsCounter = secondsCounter - 1;
remSeconds = remSeconds - 1;
$seconds.text(formatNumber(secondsCounter));
$minutes.text(formatNumber(minutesCounter));
$hours.text(formatNumber(hoursCounter));
} else {
clearInterval(_tick);
document.getElementById("tRemaining").innerHTML = "EXPIRED";
}
},
1000);
})
}
startTimers();
</script>
the seconds it skips is directly related to the number of timers i add to the page.
You're sharing these variables
var remSeconds = Math.floor(#timeRemaining);
var secondsCounter = Math.floor(remSeconds % 60);
var minutesCounter = Math.floor((remSeconds / 60) % 60);
var hoursCounter = Math.floor((remSeconds / 3600));
across all the timers. Move the declarations inside this
$timers.each(function() {
function's scope.

Trying to pause and resume a timer with same button

I am having a little trouble with this code. I am currently have a button that when clicked starts a timer. It then also changes the icon of the button from a start icon to a stop icon. I would like to stop this timer when the button is clicked again and have it switch back the icon from start to stop. I have been stuck for awhile and tried many things but cant get it to work and would appreciate any help. I am sure its a simple issue I am just new to javascript. Thanks.
(function () {
"use strict";
var minutesLabel = document.getElementById('t1-min'),
secondsLabel = document.getElementById('t1-sec'),
resetButton = document.getElementById('t1-reset'),
startButton = document.getElementById('t1-play'),
timer = null;
function getTimeRemaining(endtime) {
var t = Date.parse(endtime) - Date.parse(new Date());
var seconds = Math.floor((t / 1000) % 60);
var minutes = Math.floor((t / 1000 / 60) % 60);
return {
'total': t,
'minutes': minutes,
'seconds': seconds
};
}
function initializeClock(endtime) {
var timeinterval = setInterval(function () {
var t = getTimeRemaining(endtime);
if (t.total <= 0) {
clearInterval(timeinterval);
}
minutesLabel.innerHTML = t.minutes;
secondsLabel.innerHTML = pad(t.seconds);
}, 1000);
}
startButton.onclick = function runClock() {
var timeInMinutes = minutesLabel.innerHTML,
currentTime = Date.parse(new Date()),
deadline = new Date(currentTime + timeInMinutes * 60 * 1000);
initializeClock(deadline);
startButton.innerHTML = ('<i class="far fa-stop-circle fa-2x float-right">');
}
function pad(val) {
var valString = val + "";
if (valString.length < 2) {
return "0" + valString;
} else {
return valString;
}
}
})();
Firstly, make sure that the event listener in placed correctly on the startButton element by adding a function on addEventLister method like that:
startButton.addEventListener("click", function() {
//code goes here
});
Then initialize the timeinterval variable in the global scope of the code so that it can be accessed from all functions, and add a const in which you can save the initial text of the startButton:
(function () {
"use strict";
const START_BUTTON_INITIAL_TEXT = "Start"; // initial constant text of the start button
var minutesLabel = document.getElementById('t1-min'),
secondsLabel = document.getElementById('t1-sec'),
resetButton = document.getElementById('t1-reset'),
startButton = document.getElementById('t1-play'),
timer = null,
timeinterval; // declared in the global scope
Then add an id equal to t1-stop for the stopButton icon element to make sure that it can be accurately accessed by the Javascript file from the DOM:
startButton.innerHTML = ('<i id="t1-stop" class="far fa-stop-circle fa-2x float-right">');
lastly add this if statement in addEventListener function of startButton to check whether a stop button exists in the DOM when the startButton is clicked:
startButton.addEventListener("click", function() {
if (document.getElementById("t1-stop") != null) {
clearInterval(timeinterval);
var stopButton = document.getElementById("t1-stop");
startButton.removeChild(stopButton);
startButton.innerHTML = START_BUTTON_INITIAL_TEXT;
}
The above code stops the timeinterval and removes the stopButton from the DOM then replaces the innerHTML of startButton with the initial text set as a constant at the top variable declaration.
All in all, your event listener function for the startButton should look something like that:
startButton.addEventListener("click", function() {
if (document.getElementById("t1-stop") != null) {
clearInterval(timeinterval);
var stopButton = document.getElementById("t1-stop");
startButton.removeChild(stopButton);
startButton.innerHTML = START_BUTTON_INITIAL_TEXT;
return;
}
var timeInMinutes = minutesLabel.innerHTML,
currentTime = Date.parse(new Date()),
deadline = new Date(currentTime + timeInMinutes * 60 * 1000);
initializeClock(deadline);
startButton.innerHTML = ('<i id="t1-stop" class="far fa-stop-circle fa-2x float-right">');
});

Button onclick performing multiple actions

I have this code:
var hour = parseInt(js_arr[j].substring(0, 1));
var min = parseInt(js_arr[j].substring(3, 4));
var seconds = parseInt(js_arr[j].substring(6, 7));
var mil_sec = parseInt(js_arr[j].substring(9, 11));
var time = (hour * 3600000) + (min * 60000) + (seconds * 1000) + mil_sec;
function timeout() {
setTimeout(function () {
if (true) {
document.getElementById('subs').innerHTML = js_arr[i];
i = i + 4;
j = j + 4;
hour = parseInt(js_arr[j].substring(0, 1));
min = parseInt(js_arr[j].substring(3, 4));
seconds = parseInt(js_arr[j].substring(6, 7));
mil_sec = parseInt(js_arr[j].substring(9, 11));
time = (hour * 3600000) + (min * 60000) + (seconds * 1000) + mil_sec;
timeout();
} else {
timeout();
}
}, time);
}
Before javascript code I have an onclick="timeout(); button.
This button allows subtitles to play. What I would also like it to do is to stop these subtitles from playing by clicking on that same button. It would be great if someone could help!
Thanks a lot.
Add a variable that indicates whether the timeout is active. In the timeout()-function, this variable is checked and another loop is only initiated when it is true. To Start and Stop you simply set (and call timeout()) or reset the variable.
var hour = parseInt(js_arr[j].substring(0,1));
var min = parseInt(js_arr[j].substring(3,4));
var seconds = parseInt(js_arr[j].substring(6,7));
var mil_sec = parseInt(js_arr[j].substring(9,11));
var time = (hour*3600000)+(min*60000)+(seconds*1000)+mil_sec;
var timeOutRunning = false;
function startTimeOut() {
timeOutRunning = true;
timeout();
}
function stopTimeOut() {
timeOutRunning = false;
}
function timeout() {
if(timeOutRunning) {
setTimeout(function() {
document.getElementById('subs').innerHTML = js_arr[i];
i=i+4;
j=j+4;
hour = parseInt(js_arr[j].substring(0,1));
min = parseInt(js_arr[j].substring(3,4));
seconds = parseInt(js_arr[j].substring(6,7));
mil_sec = parseInt(js_arr[j].substring(9,11));
time = (hour*3600000)+(min*60000)+(seconds*1000)+mil_sec;
timeout();
}, time);
}
}
And then the onclick-function:
onclick="if(timeOutRunning) { stopTimeOut(); } else { startTimeOut(); }"

Categories