I am trying to display two timer on a webpage with different start times.
First timer only shows for 5 seconds and then after 10 seconds I need to show timer2.
I am very new to Angular and have put together following code.
It seems to be working fine except when the settimeout is called the third time it doesn't work correctly and it starts going very fast.
Controller
// initialise variables
$scope.tickInterval = 1000; //ms
var min ='';
var sec ='';
$scope.ti = 0;
$scope.startTimer1 = function() {
$scope.ti++;
min = (Math.floor($scope.ti/60)<10)?("0" + Math.floor($scope.ti/60)):(Math.floor($scope.ti/60));
sec = $scope.ti%60<10?("0" + $scope.ti%60):($scope.ti%60);
$scope.timer1 = min + ":" + sec;
mytimeout1 = $timeout($scope.startTimer1, $scope.tickInterval); // reset the timer
}
//start timer 1
$scope.startTimer1();
$scope.$watch('timer1',function(){
if($scope.timer1 !=undefined){
if($scope.timer1 =='00:05'){
$timeout.cancel(mytimeout1);
setInterval(function(){
$scope.startTimer2()
$scope.ti = 0;
},1000)
}
}
})
//start timer 2 after 2 mins and 20 seconds
$scope.startTimer2 = function() {
$scope.ti++;
min = (Math.floor($scope.ti/60)<10)?("0" + Math.floor($scope.ti/60)):(Math.floor($scope.ti/60));
sec = $scope.ti%60<10?("0" + $scope.ti%60):($scope.ti%60);
$scope.timer2 = min + ":" + sec;
mytimeout2 = $timeout($scope.startTimer2, $scope.tickInterval);
}
$scope.$watch('timer2',function(){
if($scope.timer2 !=undefined){
if($scope.timer2 =='00:05'){
$timeout.cancel(mytimeout2);
setInterval(function(){
$scope.startTimer1();
$scope.ti = 0;
},1000)
}
}
})
In my view I simply have
<p>{{timer1}}</p>
<p>{{timer2}}</p>
You're basically starting multiple startTimer function so it's adding up. If i understood your problem well you don't even need to have all those watchers and timeouts.
You just can use $interval this way :
$scope.Timer = $interval(function () {
++$scope.tickCount
if ($scope.tickCount <= 5) {
$scope.timer1++
} else {
$scope.timer2++
if ($scope.tickCount >= 10)
$scope.tickCount = 0;
}
}, 1000);
Working fiddle
Related
I am having an issue with reseting a JS timer in a one state app that uses ajax to load new pages, so the page rarely experiences a full reload. The timer is used to countdown the date on inquiry pages (similar concept to ebay) and there are multiple inquiry pages - all with different timers and expiry dates.
The timer works perfectly on a full page reload, but after that, it gets increasingly faster and starts storing all the different timers simultaneously (e.g. if I visited three inquiry pages and initialized three timers, now its gonna count 3 seconds per second instead of 1.)
Here is my timer function
var timer = {
isActive : null,
firstLoad : null,
currentTime: null,
distance : null,
duration : null,
init: function() {
var scope = timer;
if (scope.isActive) {
scope.counter();
}
else {
$("#countdown").html("-");
}
},
counter: function() {
var scope = timer;
scope.countdown = setInterval(function() {
if (scope.firstLoad) {
scope.distance = scope.activeTo - scope.currentTime;
scope.duration = moment.duration(scope.distance);
scope.firstLoad = false;
}
else {
scope.duration.subtract(1, "second");
}
// Time calculations for days, hours, minutes and seconds
var days = scope.duration.days();
var hours = scope.duration.hours();
if (hours < 10) {
hours = "0" + hours;
}
var minutes = scope.duration.minutes();
if (minutes < 10) {
minutes = "0" + minutes;
}
var seconds = scope.duration.seconds();
if (seconds < 10) {
seconds = "0" + seconds;
}
// Display the result in the element with id="countdown"
jQuery("#countdown").html(days + " <%= pdo.translate("countdown.days.label")%> " + hours + ":" + minutes + ":" + seconds);
// If the count down is finished, write some text
if (scope.distance < 0) {
$("#addNewBid, #cancelInquiry, #editInquiry").hide();
$("#countdown").html("<%= pdo.translate("countdown.timeend.label")%>");
}
}, 1000);
},
reset: function() {
var scope = timer;
clearInterval(scope.countdown);
scope.isActive = null;
scope.firstLoad = null;
scope.currentTime = null;
scope.distance = null;
scope.duration = null;
}
};
And this is how I reset and initialize it on new page load.
$(document).ready(function ($) {
timer.reset();
timer.currentTime = new moment("<%=pdo.getTime()%>");
timer.activeTo = new moment("<%= pdo.getInquiry().getActiveTo() %>");
timer.isActive = <%=pdo.getInquiry().isActive()%>;
timer.firstLoad = true;
timer.init();
});
I am creating an sample application, user signout time is 15 minutes.
Before 2 minute, users gets an pop with warning message with countdown.
There are two buttons.
Logout => for logout.
StayLogin => get additional 15 minutes time into the application.
For the first time , when user reaches 13 minutes, gets the popup.
So when click the proceed button, logout time gets added .
Problem :
The problem with the counter. If counter reaches 0 seconds 0 minutes it have redirect to login page.
In between the counter, user clicked, added another 15 minutes, but timer reaches 0 seconds and go to the login page.
function countdown(minutes) {
var seconds = 60;
var mins = minutes
function tick() {
var counter = document.getElementById("timer");
var current_minutes = mins - 1
seconds--;
counter.innerHTML =
current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
if (seconds === 0) {
$state.go("root"); // problem
}
if (seconds > 0) {
setTimeout(tick, 1000);
} else {
if (mins > 1) {
alert('minutes');
// countdown(mins-1); never reach “00″ issue solved:Contributed by Victor Streithorst
setTimeout(function() {
countdown(mins - 1);
}, 1000);
}
}
}
tick();
}
countdown(1); * *
// staylogin
$rootScope.proceed = function() {
var lastDigestRun = Date.now();
var s = lastDigestRun + 3 * 60 * 1000;
var displaytime = now - lastDigestRun > 3 * 60 * 1000;
if (now - lastDigestRun > 2 * 60 * 1000) {
clearTimeout(tick);
load();
}
}
How to stop the counter when click the stayLogin button?
You need to use something like
$timeout.cancel(timer)
to cancel the timer and recreate a new one.
Have a look at how I would do it below.
var app = angular.module('myApp', []);
app.controller('MainCtrl', function($scope, $timeout, $interval) {
$scope.name = 'MyConfusedUser';
$scope.firstLoad = true;
$scope.loggingOut = false;
$scope.loggOutIn = 5;
$scope.loggingOutIn = 10;
$scope.maxLoginTime = 10;
$scope.getTimer = function(seconds){
return $timeout(function(){
alert('you are logged out');
}, seconds * 1000);
}
$scope.resetTime = function(){
$timeout.cancel($scope.currentTimer);
$scope.currentTimer = $scope.getTimer($scope.maxLoginTime);
$scope.loggingOutIn = $scope.maxLoginTime;
$scope.loggingOut = false;
}
if($scope.firstLoad){
$scope.firstLoad = false;
$interval(function(){
$scope.loggingOutIn--;
if($scope.loggingOutIn < $scope.loggOutIn){
$scope.loggingOut = true;
}
}, 1000, 0);
$scope.timers = [];
$scope.currentTimer = $scope.getTimer($scope.maxLoginTime);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" ng-controller="MainCtrl">
<div ng-hide="loggingOut">
<p>Hello {{name}}!</p>
</div>
<div ng-show="loggingOut">
<p>{{name}}, you will be logged out very soon.</p>
</div>
<p>Logging out in {{loggingOutIn}} seconds</p>
<p ng-show="loggingOut"><button ng-click="resetTime()">Reset Time</button></p>
</body>
You need to pass clearTimeout a variable that references the setTimeout, rather than the callback function. e.g.
var to = setTimeout(function(){...});
clearTimeout(to);
Why not return the setTimeout form your tick function?
The timer keeps getting faster every time I reset it. I'm thinking I need to use clearTimeout but am unsure about how to implement it. Here's the code:
$(function(){
sessionmin = 25;
$("#sessionMinutes").html(sessionmin);
$("#circle").click(function() {
timeInSeconds = sessionmin * 60;
timeout();
});
})
function timeout(){
setTimeout(function () {
if (timeInSeconds > 0) {
timeInSeconds -= 1;
hours = Math.floor(timeInSeconds/3600);
minutes = Math.floor((timeInSeconds - hours*3600)/60);
seconds = Math.floor(timeInSeconds - hours*3600 - minutes*60);
$("#timer").html(hours + ":" + minutes + ":" + seconds);
}
timeout();
}, 1000);
}
You have to define your setTimeout as a variable to reset it.
See Fiddle
var thisTimer; // Variable declaration.
$(function(){
sessionmin = 25;
$("#sessionMinutes").html(sessionmin);
$("#circle").click(function(){
clearTimeout(thisTimer); // Clear previous timeout
timeInSeconds = sessionmin * 60;
timeout();
});
})
function timeout(){
thisTimer = setTimeout(function () { // define a timeout into a variable
if(timeInSeconds>0){
timeInSeconds-=1;
hours = Math.floor(timeInSeconds/3600);
minutes = Math.floor((timeInSeconds - hours)/60);
seconds = (timeInSeconds - hours*3600 - minutes*60)
$("#timer").html(hours + ":" + minutes + ":" + seconds);
}
timeout();
}, 1000);
}
You should: use setInterval instead of setTimeout, return the interval id that setInterval generates, clear that interval before you restart it. Here is an example: https://jsfiddle.net/8n2b7x0s/
$(function(){
var sessionmin = 25;
var intervalId = null;
$("#sessionMinutes").html(sessionmin);
$("#circle").click(function() {
timeInSeconds = sessionmin * 60;
// clear the current interval so your code isn't running multiple times
clearInterval(intervalId);
// restart the timer
intervalId = run();
});
})
function run(){
return setInterval(function () {
if(timeInSeconds>0){
timeInSeconds-=1;
hours = Math.floor(timeInSeconds/3600);
minutes = Math.floor((timeInSeconds - hours)/60);
seconds = (timeInSeconds - hours*3600 - minutes*60)
$("#timer").html(hours + ":" + minutes + ":" + seconds);
}
}, 1000);
}
I'm making a random "spinner" that loops through 8 divs and add a class active like this:
https://jsfiddle.net/9q1tf51g/
//create random setTimeout time from 3sec to 5sec
var time = Math.floor(Math.random() * (5000 - 3000 + 1)) + 3000;
var exit = false;
function repeat(){
//my code
if(!exit){
setTimeout(repeat, 50);
}
}
My problem is, I want the function repeat to end slowly, to create more suspense. I think I can do this by raising the 50 from the timeout but how can I do this accordingly to the time left?
Thanks in advance!
You can try this.
$('button').on('click', function(){
var time = Math.floor(Math.random() * (5000 - 3000 + 1)) + 3000;
var anCounter = 1;
var anState = "positive";
var exit = false;
//var time1 = 50000;
setInterval(function(){time = time-1000;}, 1000);
function repeat(){
if(anCounter>7 && anState=="positive"){ anState="negative"}
if(anCounter<2 && anState=="negative"){ anState="positive"}
$('div[data-id="'+anCounter+'"]').addClass('active');
$('div').not('div[data-id="'+anCounter+'"]').removeClass('active');
if(anState=="positive"){anCounter++;}else{anCounter--;}
if(!exit){
if(time <1000)
setTimeout(repeat, 300);
else if(time< 2000)
setTimeout(repeat, 100);
else setTimeout(repeat, 50);
}
}
repeat();
setTimeout(function(){
exit=true;
},time);
});
Once you know that you need to exit the flow (exit is true ) you can trigger some animation by creating a dorm linear serials of you code. Usually this animation should not last more than 2 sec.
You were kind of on the right track but it'd be easier to check the time you've passed by and increment accordingly at a fixed rate. I set it to increase by 50ms every iteration but you could change that to whatever you like.
Fiddle Demo
Javascript
$('button').on('click', function() {
var time = Math.floor(Math.random() * (5000 - 3000 + 1)) + 3000;
var anCounter = 1;
var anState = "positive";
var elapsed = 0;
var timer;
function repeat(timeAdded) {
if (anCounter > 7 && anState == "positive") {
anState = "negative"
}
if (anCounter < 2 && anState == "negative") {
anState = "positive"
}
$('div[data-id="' + anCounter + '"]').addClass('active');
$('div').not('div[data-id="' + anCounter + '"]').removeClass('active');
if (anState == "positive") {
anCounter++;
} else {
anCounter--;
}
if (elapsed < time) {
timer = setTimeout(function() {
repeat(timeAdded + 50);
}, timeAdded);
elapsed += timeAdded;
}
else {
clearTimeout(timer);
}
}
repeat(0);
});
You can add a parameter called intTime to your function repeat and inside that function you can adjust the next timeout and call the repeat function with the new timeout. each time it gets called it will take 20 ms longer. however you adjust the increment by changing the 20 in
var slowDown=20; to a different number.
var slowDown=20;
setTimeout ("repeat",50);
function repeat(intTime){
//my code
if(!exit){
intTime=Math.floor (intTime)+slowDown;
setTimeout(repeat(intTime), intTime);
}
}
And then you will need to create another timeout for the exit.
var time = Math.floor(Math.random() * (5000 - 3000 + 1)) + 3000;
var exit = false;
setTimeout ("stopSpinning",time);
function stopSpinning(){
exit = true;
}
so the whole thing should look something like this
var slowDown=20;
var time = Math.floor(Math.random() * (5000 - 3000 + 1)) + 3000;
var exit = false;
setTimeout ("stopSpinning",time);
setTimeout ("repeat",50);
function repeat(intTime){
//my code
if(!exit){
intTime=Math.floor (intTime)+20;
setTimeout(repeat(intTime), intTime);
}
}
function stopSpinning(){
exit = true;
}
Fiddle Demo
Linear deceleration: //values are just an example:
add a var slowDown = 0; inside the click event handler
add slowDown += 1; inside the repeat function
pass 50+slowDown to setTimeout
Curved deceleration:
add a var slowDown = 1;and a var curveIndex = 1.05 + Math.random() * (0.2); // [1.05-1.25)inside the click event handler
add slowDown *= curveIndex; inside the repeat function
pass 50+slowDown to setTimeout
I'm trying to implement a script that essentially counts down from 30 seconds to 0, and at 0, redirects to the homepage. However, I noticed that my script only works on Firefox but not Chrome and Safari. On these browsers, the counter remains "stuck" at 30 seconds—never refreshing the HTML, but the redirect works fine. Not sure if I'm doing something wrong or if setInterval is not the right method for this kind of thing.
<script>
var seconds = 31;
var counter = setInterval("timer()", 1000);
function timer() {
seconds = seconds - 1;
if (seconds < 0) {
setTimeout("location.href='http://www.homepage.com';", 100);
return;
}
updateTimer();
}
function updateTimer() {
document.getElementById('timer').innerHTML = "Redirecting in " + " " + seconds + " " + "seconds";
}
</script>
Thanks in advance!
EDIT: So weirdly enough, my code (and all of yours) is working on JSFiddle, but it's just failing to "repaint" the HTMLinner when it's actually rendering the page. The seconds are changing fine (I outputted them to the console), the changes just aren't rendering.
Final Edit: This problem basically resulted from invalid CSS. I believe—the counter was running above the photo and I set the span to relative positioning with a higher z-index and top and bottom elements. I don't believe this is acceptable for something that is not a block.
Here's a working sample:
(function() { // wrapper for locals
var timer = document.getElementById("timer"),
seconds = 5,
counter = setInterval(function() {
if (--seconds < 1) {
clearInterval(counter);
timer.innerHTML = "Redirecting now...";
setTimeout(function() {
location.href = 'http://www.homepage.com';
}, 500);
} else {
timer.innerHTML = timer.innerHTML.replace(/\d+/, seconds);
}
}, 1000);
})();
<div id="timer">Redirecting in 5 seconds</div>
Here is a cleaner implementation with fewer defined functions (with demo):
<span id='timer'></span>
<script>
var seconds = 31;
setInterval(function() {
seconds = seconds - 1;
if (seconds < 0) {
setTimeout(function() {document.getElementById('timer').innerHTML = "redirecting..."}, 100);
return;
}
updateTimer();
}, 1000);
function updateTimer() {
document.getElementById('timer').innerHTML = "Redirecting in " + + seconds + " seconds";
}
<script>
Of course every JavaScript programmer should any opportunity to point out that "eval is evil" which includes passing a string to setInterval and setTimeout :)
Change your function to a variable, that worked for me:
<script>
var seconds = 31;
var counter = setInterval(timer, 1000);
var timer = function() {
seconds = seconds - 1;
if (seconds < 0) {
setTimeout("location.href='http://www.homepage.com';", 100);
return;
}
updateTimer();
}
function updateTimer() {
document.getElementById('timer').innerHTML = "Redirecting in " + " " + seconds + " " + "seconds";
}
</script>