I am trying to setup a limit on my slides, as it stands i have added data-ng-repeat="job in jobs | limitTo : 10"i noticing 12 slides are still displaying. Is there something incorrect my code for this function not to work Plunkr
var timer;
$scope.startAuto = function() {
timer = $interval(function(){
$scope.jobNotification = ($scope.jobNotification + 1) % $scope.jobs.length;
}, 5000);
};
$scope.isActive = function (index) {
return $scope.jobNotification === index;
};
$scope.showJobNotification = function (index) {
if (timer){
$interval.cancel(timer);
$scope.startAuto();
}
$scope.jobNotification = index;
};
$scope.stopAuto = function() {
console.log('tickCtrl.stopAuto() triggered');
if(timer) {
$interval.cancel(timer);
timer = undefined;
}
}
You need to limit the jobNotification value. Reducing the modulo to 10 prevents slide 11 and 12 from ever showing.
$scope.jobNotification = ($scope.jobNotification + 1) % 10;
Related
I create plugin something like this
timer plugin
(function($) {
$.fn.timer = function(options) {
var defaults = {
seconds: 60
};
var options = $.extend(defaults, options);
return this.each(function() {
var seconds = options.seconds;
var $this = $(this);
var timerIntval;
var Timer = {
setTimer : function() {
clearInterval(timerIntval);
if(seconds <= 0) {
alert("timeout");
}else {
timerIntval = setInterval(function(){
return Timer.getTimer();
}, 1000);
}
},
getTimer : function () {
if (seconds <= 0) {
$this.html("0");
} else {
seconds--;
$this.html(seconds);
}
}
}
Timer.setTimer();
});
};
})(jQuery);
and I call the plugin like this.
$(".myTimer").timer({
seconds : 100
});
i called the plugin at timerpage.php. When i changed the page to xxx.php by clicking another menu, the timer interval is still running and i need to the clear the timer interval.
i created a webpage using jquery ajax load. so my page was not refreshing when i change to another menu.
my question is, how to clear the timer interval or destroy the plugin when i click another menu?
Please try with following modifications:
timer plugin:
(function($) {
$.fn.timer = function(options) {
var defaults = {
seconds: 60
};
var options = $.extend(defaults, options);
return this.each(function() {
var seconds = options.seconds;
var $this = $(this);
var timerIntval;
var Timer = {
setTimer : function() {
clearInterval(timerIntval);
if(seconds <= 0) {
alert("timeout");
}else {
timerIntval = setInterval(function(){
return Timer.setTimer();
}, 1000);
$this.data("timerIntvalReference", timerIntval); //saving the timer reference for future use
}
},
getTimer : function () {
if (seconds <= 0) {
$this.html("0");
} else {
seconds--;
$this.html(seconds);
}
}
}
Timer.setTimer();
});
};
})(jQuery);
Now in some other JS code which is going to change the div content
var intervalRef = $(".myTimer").data("timerIntvalReference"); //grab the interval reference
clearInterval(intervalRef); //clear the old interval reference
//code to change the div content on menu change
For clearing timer associated with multiple DOM element, you may check below code:
//iterate ovel all timer element:
$("h3[class^=timer]").each(function(){
var intervalRef = $(this).data("timerIntvalReference"); //grab the interval reference
clearInterval(intervalRef);
});
Hope this will give an idea to deal with this situation.
Instead of var timerIntval; set the variable timerInterval on the window object, then you will have the access this variable until the next refresh.
window.timerIntval = setInterval(function() {
Then when the user clicks on any item menu you can clear it:
$('menu a').click(function() {
clearInterval(window.timerIntval);
});
Live example (with multiple intervals)
$('menu a').click(function(e) {
e.preventDefault();
console.log(window.intervals);
for (var i = 0; i < window.intervals.length; i++) {
clearInterval(window.intervals[i]);
}
});
(function($) {
$.fn.timer = function(options) {
var defaults = {
seconds: 60
};
var options = $.extend(defaults, options);
return this.each(function() {
if (!window.intervals) {
window.intervals = [];
}
var intervalId = -1;
var seconds = options.seconds;
var $this = $(this);
var Timer = {
setTimer : function() {
clearInterval(intervalId);
if(seconds <= 0) {
alert("timeout");
} else {
intervalId = setInterval(function(){
//Timer.getTimer();
return Timer.getTimer();
}, 1000);
window.intervals.push(intervalId);
}
},
getTimer : function () {
if (seconds <= 0) {
$this.html("0");
} else {
seconds--;
$this.html(seconds);
}
}
}
Timer.setTimer();
});
};
})(jQuery);
$(".myTimer").timer({
seconds : 100
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<menu>
Menu 1
</menu>
<div class="myTimer"></div>
<div class="myTimer"></div>
Just notice that it's little bit risky because you can only run it once otherwise the interval id of the second will override the first.
I have this angularJS app which has a countdown timer. I want to execute a function after it becomes zero. It currently goes into negative after it reaches 0. How to achieve this?
Angular Code:
myApp.controller('MyController', ['$scope', '$timeout' ,function($scope, $http, $routeParams, $timeout) {
$scope.counter = 5000;
$scope.onTimeout = function(){
$scope.counter--;
mytimeout = $timeout($scope.onTimeout,1000);
}
var mytimeout = $timeout($scope.onTimeout,1000);
}
}]);
testControllers.filter('formatTimer', function() {
return function(input)
{
function z(n) {return (n<10? '0' : '') + n;}
var seconds = input % 60;
var minutes = Math.floor(input / 60);
var hours = Math.floor(minutes / 60);
return (z(hours) +':'+z(minutes)+':'+z(seconds));
};
});
HTML:
<div><p>{{counter|formatTimer}}</p></div>
Simply stop calling it when the counter is 0:
$scope.onTimeout = function(){
if (--$scope.counter > 0) {
$timeout($scope.onTimeout, 1000);
} else {
// Call your function now that counter is 0
}
}
Depending on what else you are doing, you probably don't need to put your timeout method on the scope. Also, look at $interval instead. It's better suited for calling something continuously.
function decreaseCounter() {
if(--$scope.counter <= 0) {
$interval.cancel(intervalPromise);
yourOtherFunction();
}
}
var intervalPromise = $interval(decreaseCounter, 1000);
https://docs.angularjs.org/api/ng/service/$interval
If you need a precise countdown (specially if the time span is large) you need to calculate the time spent using Date time function. Simply incrementing a counter each 1000 milliseconds 5000 times, doesen't guarantee that at the end, the real time spent will be exactly 5000 seconds!
You could try something like this:
Controller:
function MyCtrl($scope, $interval) {
var intervalId;
$scope.counter = 0;
$scope.initialCountdown = 10;
$scope.countdown = $scope.initialCountdown;
$scope.timer = function(){
var startTime = new Date();
intervalId = $interval(function(){
var actualTime = new Date();
$scope.counter = Math.floor((actualTime - startTime) / 1000);
$scope.countdown = $scope.initialCountdown - $scope.counter;
}, 1000);
};
$scope.$watch('countdown', function(countdown){
if (countdown === 0){
$scope.stop();
}
});
$scope.start = function(){
$scope.timer();
};
$scope.stop = function(){
$interval.cancel(intervalId);
};
}
View:
<div ng-controller="MyCtrl">
<div>Counter: {{counter}}</div>
<div>Countdown in seconds: {{countdown}}</div>
<div>Countdown date time: {{countdown | secondsToDateTime | date:'HH:mm:ss'}}</div>
<button ng-click="start()">start</button>
<button ng-click="stop()">stop</button>
</div>
Filter secondsToDateTime:
myApp.filter('secondsToDateTime', [function() {
return function(seconds) {
return new Date(1970, 0, 1).setSeconds(seconds);
};
}])
CHECK THE DEMO FIDDLE
Enjoy!
I'm working on a little "web app" for a quiz.
Each slide has got a certain amount of time to be answered (or 0 to infinite time).
I find JS here to do the countdown:
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);
};
}
var myCounter = new Countdown({
seconds: timetogo, // number of seconds to count down
onUpdateStatus: function (sec) {
elapsed = timetogo - sec;
$('.progress-bar').width(((elapsed / timetogo) * 100) + "%");
}, // callback for each second
onCounterEnd: function () {
//alert('counter ended!');
} // final action
});
myCounter.start();
I made a jsfiddle here :
https://jsfiddle.net/mitchum/kz2400cc/2/
But i am having trouble when you go to the next slide, the progress bar "bump".
after looking into "live source panel from chrome" I saw it's like the first "counter" is not stopped and still runs.
Do you have any tips or hint to help me to solve my bug ?
Thanks
You must pay attention to the scope of the variables. I change the "var myCounter" under document ready in "var myCounterFirst". Check the updated JSFiddle.
var timetogoFirst = $('.current').attr("data-time");
var myCounterFirst = new Countdown({
seconds: timetogoFirst, // number of seconds to count down
onUpdateStatus: function (sec) {
elapsed = timetogoFirst - sec;
$('.progress-bar').width(((elapsed / timetogoFirst) * 100) + "%");
}, // callback for each second
onCounterEnd: function () {
alert('counter ended!');
} // final action
});
myCounterFirst.start();
Need some help with my code, I can't get my alerts to work with my countdown timer. They should be alerting at 4,3,2 minutes left on the timer. I currently can't get the alerts to fire at all, sometimes they would fire but each second after 4, the alert for "4" would fire. I need it to just go once... Any help would be appreciated
Heres my script
var running=false
var endTime=null
var timerID=null
function startTimer(){
running=true
now=new Date()
now=now.getTime()
endTime=now+(1000*60*5)
showCountDown()
}
function showCountDown(){
var now=new Date()
now=now.getTime()
if (endTime-now<=239990 && endTime-now>240010){alert("4")};
if (endTime-now<=179990 && endTime-now>180010){alert("3")};
if (endTime-now<=119990 && endTime-now>120010){alert("2")};
if (endTime-now<=0){
stopTimer()
alert("Time is up. Put down pencils")
} else {
var delta=new Date(endTime-now)
var theMin=delta.getMinutes()
var theSec=delta.getSeconds()
var theTime=theMin
theTime+=((theSec<10)?":0" : ":")+theSec
document.forms[0].timerDisplay.value=theTime
if (running){
timeID=setTimeout("showCountDown()",1000)
}
}
}
function stopTimer(){
clearTimeout(timeID)
running=false
document.forms[0].timerDisplay.value="0.00"
}
Update, Sorry meant minutes instead of seconds
Update 2: Change the ifs, now they fire but keep firing after the 4 second mark
if (endTime-now<=240010 && endTime-now<=239990){alert("4")};
if (endTime-now<=180010 && endTime-now<=179990){alert("3")};
if (endTime-now<=120010 && endTime-now<=119990){alert("2")};
Why are you calling clearTimeout? setTimeout invokes its callback only once. There is no need to clear it. Also you could just have a variable that stores the minutes until the end of the countdown and decrement that by one in each iteration.
The simplest solution might look like this
function startTimer(minutesToEnd) {
if(minutesToEnd > 0) {
if(minutesToEnd <= 4) {
console.log(minutesToEnd);
}
setTimeout(startTimer, 60000, minutesToEnd - 1);
} else {
console.log("Time is up. Put down pencils")
}
}
I actually spent some time working on this. I have no idea if this is what you wanted, but I created a timer library. I have a working demo for you. I had fun making this. Let me know what you think:
JS:
(function () {
var t = function (o) {
if (!(this instanceof t)) {
return new t(o);
}
this.target = o.target || null;
this.message = o.message;
this.endMessage = o.endMessage;
//setInterval id
this.si = -1;
//Initial start and end
this.startTime = null;
this.endTime = null;
this.interTime = null;
this.duration = o.duration || 1000 * 60 * 5;
//looping speed miliseconds it is best to put the loop at a faster speed so it doesn't miss out on something
this.loop = o.loop || 300;
//showing results miliseconds
this.show = o.show || 1000;
};
t.fn = t.prototype = {
init: function () {}
};
//exporting
window.t = t;
})();
//Timer Functions ---
t.fn.start = function () {
this.startTime = new Date();
this.interTime = this.startTime.getTime();
this.endTime = new Date().setMilliseconds(this.startTime.getMilliseconds() + this.duration);
//returns undefined... for some reason.
console.log(this.endTime);
var $this = this;
this.writeMessage(this.duration);
this.si = setInterval(function () {
var current = new Date(),
milli = current.getTime();
if (milli - $this.interTime >= $this.show) {
var left = $this.endTime- milli;
if (left <= 0) {
$this.stop();
} else {
$this.interTime = milli;
$this.writeMessage(left);
}
}
}, this.loop);
return this;
};
t.fn.writeMessage = function(left){
this.target.innerHTML = this.message + ' ' + Math.floor(left / 1000);
return this;
};
t.fn.stop = function () {
//stopping the timer
clearInterval(this.si);
this.target.innerHTML = this.endMessage;
return this;
};
//Not chainable
t.fn.isRunning = function () {
return this.timer > -1;
};
var timer = t({
target: document.getElementById('results'),
loop: 50,
duration: 10000,
show: 1000, //default is at 1000 miliseconds
message: 'Time left: ', //If this is ommited then only the time left will be shown
endMessage: 'Time is up. Put down your pencils'
}).start();
document.getElementById('stop').onclick = function(){
timer.stop();
};
HTML:
<div id="results"></div>
<button id="stop">Stop</button>
Demo here
Update: I added some stuff
Demo 2
Update 2: I fixed the bug where 10 would hop straight to 8
Demo 3
I've built a very simply slider with Angular like so:
$scope.slider = {};
$scope.slider.pane = 1;
$scope.slider.auto = true;
var slider = function(){
$timeout(function(){
if ($scope.slider.pane === 4) $scope.slider.pane = 1;
else $scope.slider.pane ++;
slider();
}, 4000);
}
slider();
The slider function creates a timeout loop to change the value of slider.pane every 4s. In the HTML I have a link that when clicked sets the value slider.auto to false.
Stop slider
When this is clicked, it needs to stop the timeout loop. It may be in the middle of a cycle at the time, so I need to clear the timeout, but it's inside a function so not sure how to access it.
Use the $timeout.cancel function:
var timeout;
$scope.cancelTimer = function() {
$scope.slider.auto=false;
$timeout.cancel(timeout);
};
var slider = function(){
timeout = $timeout(function(){
if ($scope.slider.pane === 4) $scope.slider.pane = 1;
else $scope.slider.pane ++;
slider();
}, 4000);
}
slider();
//HTML
Stop slider
Try:
$scope.slider = {};
$scope.slider.pane = 1;
$scope.slider.auto = true;
var promise;
var slider = function(){
promise = $timeout(function(){
if ($scope.slider.pane === 4) $scope.slider.pane = 1;
else $scope.slider.pane ++;
slider();
}, 4000);
}
$scope.autoSliderFalse = function() {
$scope.slider.auto = false;
if(promise)
$timeout.cancel(promise);
});
slider();
HTML
Stop slider
You can use the cancel method as some people suggested here.
I actually think in your case you should use $interval instead of $timeout.
var interval = $interval(function(){
if ($scope.slider.pane === 4) {
$scope.slider.pane = 1;
}
else {
$scope.slider.pane ++;
}
}, 4000);
$scope.stopSlider = function(){
$interval.cancel(interval);
};
//html
Stop slider