Refresh "Time function" - javascript

My function is supposed to switch when she is working. Basically , it's 11pm , she is supposed to switch if it's 11:01pm but i have to reload the app to make it work. Do you know how to switch the function without reload all the app ?
startMatchOrStop = () => {
return this.state.sport.clubs.map((element) => {
var dateMatch = new Date(element.dateMatch).getTime();
var dateMatchStop = new Date(element.dateMatchStop).getTime();
var today = Date.now();
console.log(dateMatch);
console.log(dateMatchStop);
console.log(today);
if (today >= dateMatch && today < dateMatchStop) {
return (
this.setState({soundCapture: true}),
RNSoundLevel.start(),
(RNSoundLevel.onNewFrame = (data) => {
this.setState({soundArray: data.value});
this.PostDecibels();
console.log(today >= dateMatchStop);
})
);
} else {
return (
console.log(today <= dateMatchStop),
RNSoundLevel.stop(),
this.setState({soundCapture: false}),
Alert.alert('Titre', 'Match Fini enregistrement terminé')
);
}
});
};

If you want your function to re-run again
you may put it inside interval
and check it every X seconds for Y time(s).
for example:
var retryCount = 3;
var startFuncInt = setInterval(() => {
if (--retry){
startMatchOrStop();
}
else{
window.clearInterval(startFuncInt);
}
}, 1000);

Related

Would like to make my progressbar as smooth as possible

Can anyone help me make this progessbar smoother?
This is my javascript code for the progressbar. I hope you can do something with it and help me with it.
I would like to improve the smoothness because it is very stuttering at a higher runtime.
window.addEventListener('message', (event) => {
var item = event.data;
if (item !== undefined && item.type === "ui") {
if (item.display === true) {
$(".container").fadeIn(700);
var start = new Date();
var title = item.title;
var maxTime = item.time;
var text = item.text;
var timeoutVal = Math.floor(maxTime/100);
animateUpdate();
$('#notifyMsg').text(text);
$('#notifyHead').text(title);
function updateProgress(percentage) {
$('#progb').css("width", percentage + "%");
}
function animateUpdate() {
var now = new Date();
var timeDiff = now.getTime() - start.getTime();
var perc = Math.round((timeDiff/maxTime)*100);
if (perc <= 100) {
updateProgress(perc);
setTimeout(animateUpdate, timeoutVal);
} else {
$(".container").fadeOut(700);
}
}
} else {
$("#container").hide();
}
}
});
You should use window.requestAnimationFrame instead of setTimeout. This function runs on every animation cycle.
And adjust your animateUpdate function.
function animateUpdate() {
var now = new Date();
var timeDiff = now.getTime() - start.getTime();
var perc = Math.round((timeDiff/maxTime)*100);
if (perc <= 100) {
updateProgress(perc);
// Changed this line
window.requestAnimationFrame(animateUpdate)
} else {
$(".container").fadeOut(700);
}
}
Here are the docs of window.requestAnimationFrame.

Countdown timer stops when switching tabs

So basically when I switch tabs, the countdown timer on a specific page just stops counting down and resumes when you return to the tab. Is there anyway to mitigate that so that it counts in the background or it accounts for the time you spend on another tab?
This is basically what I have for js:
document.getElementById('timer').innerHTML =
05 + ":" + 01;
startTimer();
function startTimer() {
var presentTime = document.getElementById('timer').innerHTML;
var timeArray = presentTime.split(/[:]+/);
var m = timeArray[0];
var s = checkSecond((timeArray[1] - 1));
if(s==59){m=m-1}
if(m<0){
return
} else if (m == 0 && s == 0) {
location.reload();
}
document.getElementById('timer').innerHTML =
m + ":" + s;
setTimeout(startTimer, 1000);
}
function checkSecond(sec) {
if (sec < 10 && sec >= 0) {sec = "0" + sec};
if (sec < 0) {sec = "59"};
return sec;
}
Any ideas whether the time could be done server side or something so that it can't be modified client side? If not, then whatever, but mainly just want to figure out how to make the countdown still work (or account for the time spent) when on another tab.
We can store the variable m and s values either globally or use the local storage to set the values after setting the inner HTML and get the stored values back whenever tabs were switched as:
Set values:
window.localStorage.setItem('minutes', m.toString()); //same for the seconds
Get values:
window.localStorage.getItem('minutes'); //same for the seconds
Hope this answers your questions.
Just a simple solution:
Add this piece of code.
<html>
<head>
<script>
(function() {
var $momentum;
function createWorker() {
var containerFunction = function() {
var idMap = {};
self.onmessage = function(e) {
if (e.data.type === 'setInterval') {
idMap[e.data.id] = setInterval(function() {
self.postMessage({
type: 'fire',
id: e.data.id
});
}, e.data.delay);
} else if (e.data.type === 'clearInterval') {
clearInterval(idMap[e.data.id]);
delete idMap[e.data.id];
} else if (e.data.type === 'setTimeout') {
idMap[e.data.id] = setTimeout(function() {
self.postMessage({
type: 'fire',
id: e.data.id
});
// remove reference to this timeout after is finished
delete idMap[e.data.id];
}, e.data.delay);
} else if (e.data.type === 'clearCallback') {
clearTimeout(idMap[e.data.id]);
delete idMap[e.data.id];
}
};
};
return new Worker(URL.createObjectURL(new Blob([
'(',
containerFunction.toString(),
')();'
], {
type: 'application/javascript'
})));
}
$momentum = {
worker: createWorker(),
idToCallback: {},
currentId: 0
};
function generateId() {
return $momentum.currentId++;
}
function patchedSetInterval(callback, delay) {
var intervalId = generateId();
$momentum.idToCallback[intervalId] = callback;
$momentum.worker.postMessage({
type: 'setInterval',
delay: delay,
id: intervalId
});
return intervalId;
}
function patchedClearInterval(intervalId) {
$momentum.worker.postMessage({
type: 'clearInterval',
id: intervalId
});
delete $momentum.idToCallback[intervalId];
}
function patchedSetTimeout(callback, delay) {
var intervalId = generateId();
$momentum.idToCallback[intervalId] = function() {
callback();
delete $momentum.idToCallback[intervalId];
};
$momentum.worker.postMessage({
type: 'setTimeout',
delay: delay,
id: intervalId
});
return intervalId;
}
function patchedClearTimeout(intervalId) {
$momentum.worker.postMessage({
type: 'clearInterval',
id: intervalId
});
delete $momentum.idToCallback[intervalId];
}
$momentum.worker.onmessage = function(e) {
if (e.data.type === 'fire') {
$momentum.idToCallback[e.data.id]();
}
};
window.$momentum = $momentum;
window.setInterval = patchedSetInterval;
window.clearInterval = patchedClearInterval;
window.setTimeout = patchedSetTimeout;
window.clearTimeout = patchedClearTimeout;
})();
</script>
</head>
</html>

Timer not binding DOM value in AngularJS

I'm a backend developer, who's trying hard to make a timer by comparing two different date formats. This part of the script is working great, but whenever I try to make recursive call, nothing is binding.
I almost tried everything, from passing it into a function, using the $interval, the setInterval, and on and on. The main reason is I cannot get the value of its loop, and binding into my DOM.
Here is some of my code. Here I set all variables for the countDown() function.
$scope.timer.list = {};
$scope.timer.date = new Date();
$scope.timer.list.D = '00';
$scope.timer.list.M = '00';
$scope.timer.list.Y = '00';
$scope.timer.list.h = '00';
$scope.timer.list.m = '00';
$scope.timer.list.s = '00';
$scope.begin = {};
$scope.begin.date = {};
$scope.begin.timer = {};
$scope.counter = {
show : false,
text : '00:00'
};
setInterval(function() {
$scope.obj = {
show : $scope.countDown($scope.privateshowcase.begin_at).show,
text : $scope.countDown($scope.privateshowcase.begin_at).text
}
$scope.counter = $scope.obj;
}, 1000);
Then, here is the function:
$scope.countDown = function(begin) {
$scope.timer.date = new Date();
$scope.timer.list.D = $filter('date')($scope.timer.date, 'dd');
$scope.timer.list.M = $filter('date')($scope.timer.date, 'MM');
$scope.timer.list.Y = $filter('date')($scope.timer.date, 'yyyy');
$scope.timer.list.h = $filter('date')($scope.timer.date, 'HH');
$scope.timer.list.m = $filter('date')($scope.timer.date, 'mm');
$scope.timer.list.s = $filter('date')($scope.timer.date, 'ss');
$scope.begin.full = begin.split(" ");
$scope.begin.date = $scope.begin.full[0].split("-");
$scope.begin.timer = $scope.begin.full[1].split(":");
$scope.begin.D = $scope.begin.date[2];
$scope.begin.M = $scope.begin.date[1];
$scope.begin.Y = $scope.begin.date[0];
$scope.begin.h = $scope.begin.timer[0];
$scope.begin.m = $scope.begin.timer[1];
$scope.begin.s = $scope.begin.timer[2];
if($scope.timer.list.Y == $scope.begin.Y) {
if($scope.timer.list.M == $scope.begin.M) {
if($scope.timer.list.D == $scope.begin.D) {
$scope.counter.diff_h = $scope.timer.list.h - $scope.begin.h;
if($scope.counter.diff_h == 0 || $scope.counter.diff_h == -1) {
if($scope.counter.diff_h == 0) {
if($scope.timer.list.m > $scope.begin.m) {
$scope.counter.show = false;
$scope.counter.text = false;
} else if ($scope.timer.list.m <= $scope.begin.m) {
$scope.counter.show = true;
$scope.counter.diff_m = $scope.begin.m - $scope.timer.list.m;
if($scope.counter.diff_m <= 30) {
$scope.counter.diff_s = 60 - $scope.timer.list.s;
if($scope.counter.diff_s == 60) {
$scope.counter.s = "00";
$scope.counter.diff_m_f = $scope.counter.diff_m + 1;
} else if($scope.counter.diff_s >= 1 && $scope.counter.diff_s <= 9) {
$scope.counter.s = "0" + $scope.counter.diff_s;
$scope.counter.diff_m_f = $scope.counter.diff_m;
} else {
$scope.counter.s = $scope.counter.diff_s;
$scope.counter.diff_m_f = $scope.counter.diff_m;
}
if($scope.counter.diff_m_f >= 1 && $scope.counter.diff_m_f <= 9) {
$scope.counter.m = "0" + $scope.counter.diff_m_f;
} else {
$scope.counter.m = $scope.counter.diff_m_f;
}
}
$scope.counter.text = $scope.counter.m + ":" +$scope.counter.s;
} else {
$scope.counter.show = false;
$scope.counter.text = false;
}
} else if ($scope.counter.diff_h == -1) {
$scope.counter.diff_timer = $scope.timer.m - 60;
$scope.counter.diff_m = $scope.begin.m - $scope.counter.diff_timer;
if($scope.counter.diff_m > 30) {
$scope.counter.show = false;
$scope.counter.text = false;
} else if($scope.counter.diff_m <= 30) {
$scope.counter.show = true;
$scope.counter.diff_timer_s = $scope.timer.s - 60;
if($scope.counter.diff_timer_s == 60) {
$scope.counter.s = "00";
$scope.counter.m = $scope.counter.diff_m + 1;
} else if($scope.counter.s >= 1 && $scope.counter.s <= 9) {
$scope.counter.s = "0" + $scope.counter.diff_timer_s;
$scope.counter.m = $scope.counter.diff_m;
} else {
$scope.counter.s = $scope.counter.diff_timer_s;
$scope.counter.m = $scope.counter.diff_m;
}
$scope.counter.text = $scope.counter.m + ":" +$scope.counter.s;
} else {
$scope.counter.show = false;
$scope.counter.text = false;
}
} else {
$scope.counter.show = false;
$scope.counter.text = false;
}
} else {
$scope.counter.show = false;
$scope.counter.text = false;
}
} else {
$scope.counter.show = false;
$scope.counter.text = false;
}
} else {
$scope.counter.show = false;
$scope.counter.text = false;
}
} else {
$scope.counter.show = false;
$scope.counter.text = false;
}
return $scope.counter = {
show : $scope.counter.show,
text : $scope.counter.text
};
}
'begin' is : 'YYYY/MM/DAY HH:MM:SS'
Maybe my way of thinking is not the good one, but at list I have a very functional timer, which replace every 1 to 9 into 01 to 09, convert the 60 into 00, can compare 2 different hours.
I think you are over complicating things a little bit. I came up with a simple countDown component made in angularjs 1.6.0 (it can be done with directives for angularjs older versions as well) that compares an input Date with the now Date.
You can play around with the input and change dates to see changes happen on the component, as long as you don't break the date format.
Note on dates: simple way to compare dates:
var date0 = new Date("2017-09-12T14:45:00.640Z");
var date1 = new Date("2017-09-13T14:45:00.640Z");
var dateDiff = new Date(date1.getTime() - date0.getTime());
// "1970-01-02T00:00:00.000Z"
Although dateDiff looks weird, it's basically one day from the zero date 1970-01-01T00:00:00.000Z.
Given that, you just let angularjs do the magic (or maybe trick).
{{ dateDiff | date:"d \'days\' hh:mm:ss" }}
Besides, if you don't want to work with dates in the natural form of javascript, you can use angularjs-moment which provide you date and time utility from momentjs regardless of javascript dates pitfalls.
Here is the working code:
angular
.module('app', [])
.run(function($rootScope) {
$rootScope.countDownToDate = new Date().addDays(2);
})
.component('countDown', {
template: '{{ $ctrl.timer | date:"d \'days\' hh:mm:ss" }}',
bindings: {
to: '<'
},
controller: function CountDownCtrl($interval) {
var $this = this;
this.$onInit = function() {
$interval($this.setTime, 1000);
};
$this.setTime = function() {
$this.timer = new Date(new Date($this.to).getTime() - new Date().getTime());
}
}
});
// bootstrap the app
angular.element(function() {
angular.bootstrap(document, ['app']);
});
// extension to add days on date
Date.prototype.addDays = function(days) {
var dat = new Date(this.valueOf());
dat.setDate(dat.getDate() + days);
return dat;
};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.js"></script>
<div>
<center>
<h1>
<count-down to="countDownToDate" />
</h1>
<label for="countDownToDate">To Date</label>
<input type="datetime" name="countDownToDate" ng-model="countDownToDate">
</center>
</div>

JS- Countdown Timer Alerts

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

jquery conflict with js script

welcome all ,
i have a problem with my images slider , it runs successfuly until poll script excuted then it stops , tried to combine both scripts didn't work also tried to use noConflict but in stops both of them .
this is the slider
(function ($) {
$.fn.s3Slider = function (vars) {
var element = this;
var timeOut = (vars.timeOut != undefined) ? vars.timeOut : 4000;
var current = null;
var timeOutFn = null;
var faderStat = true;
var mOver = false;
var items = $("#sliderContent .sliderImage");
var itemsSpan = $("#sliderContent .sliderImage span");
items.each(function (i) {
$(items[i]).mouseover(function () {
mOver = true
});
$(items[i]).mouseout(function () {
mOver = false;
fadeElement(true)
})
});
var fadeElement = function (isMouseOut) {
var thisTimeOut = (isMouseOut) ? (timeOut / 2) : timeOut;
thisTimeOut = (faderStat) ? 10 : thisTimeOut;
if (items.length > 0) {
timeOutFn = setTimeout(makeSlider, thisTimeOut)
} else {
console.log("Poof..")
}
};
var makeSlider = function () {
current = (current != null) ? current : items[(items.length - 1)];
var currNo = jQuery.inArray(current, items) + 1;
currNo = (currNo == items.length) ? 0 : (currNo - 1);
var newMargin = $(element).width() * currNo;
if (faderStat == true) {
if (!mOver) {
$(items[currNo]).fadeIn((timeOut / 6), function () {
if ($(itemsSpan[currNo]).css("bottom") == 0) {
$(itemsSpan[currNo]).slideUp((timeOut / 6), function () {
faderStat = false;
current = items[currNo];
if (!mOver) {
fadeElement(false)
}
})
} else {
$(itemsSpan[currNo]).slideDown((timeOut / 6), function () {
faderStat = false;
current = items[currNo];
if (!mOver) {
fadeElement(false)
}
})
}
})
}
} else {
if (!mOver) {
if ($(itemsSpan[currNo]).css("bottom") == 0) {
$(itemsSpan[currNo]).slideDown((timeOut / 6), function () {
$(items[currNo]).fadeOut((timeOut / 6), function () {
faderStat = true;
current = items[(currNo + 1)];
if (!mOver) {
fadeElement(false)
}
})
})
} else {
$(itemsSpan[currNo]).slideUp((timeOut / 6), function () {
$(items[currNo]).fadeOut((timeOut / 6), function () {
faderStat = true;
current = items[(currNo + 1)];
if (!mOver) {
fadeElement(false)
}
})
})
}
}
}
};
makeSlider()
}
})(jQuery);
and this is the poll script
window.onload = function() {
$(".sidePollCon").load("ar_poll.html", function(r, s, xhr) {
if (s == "error") {
$(".sidePollCon").load("poll.html");
} else {
$(".vote_booroo").html("صوت الان");
$(".viewresults").html("شاهد النتيجة");
$("fieldset p").html("");
$(".results_booroo p").html("");
$(".result_booroo").attr("src", "../images/poll_color.jpg");
}
});
};
One potential problem could be the window.onload assignment. It is very prone to conflict.
Every time you do window.onload = the previous assignemnt will be overridden. See demo here:
The output shows that the first window.onload assignment never gets called, while the jQuery alternative does get called.
jQuery.noConflict does little in this regard. All it does is to prevent override the $ symbol so that another lib can use it.
So if you are also using the window.onload event to invoke the slider, then you have conflict. You can easily solve this problem by using the jquery format:
$(window).load(function() {
...
});
However usually you would tie the event to $(document).load(function(){...}); or in short form: $(function(){...}).
So for your poll that would be:
$(function(){
$(".sidePollCon").load("ar_poll.html", function(r, s, xhr) {
if (s == "error") {
$(".sidePollCon").load("poll.html");
} else {
$(".vote_booroo").html("صوت الان");
$(".viewresults").html("شاهد النتيجة");
$("fieldset p").html("");
$(".results_booroo p").html("");
$(".result_booroo").attr("src", "../images/poll_color.jpg");
}
});
});
Hope that helps.
resolving conflicts in jquery (possibly with another JS library .. like script.aculo.us) can be resolved using noconflict()
http://api.jquery.com/jQuery.noConflict/
$.noConflict();
but make sure that u have no error in your javascript code itself. use firebug and
console.log('') to test your script.

Categories