Would like to make my progressbar as smooth as possible - javascript

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.

Related

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>

localStorage how to save countdown value so it wont reset when I reload the page

When I reload the page, my 1 minute countdown also reloads.
I tried to use localStorage but it seems to me failed.
Please have a look, I do not know where I should fix.
Thank you
My script
/* for countdown */
var countDown = (function ($) {
// Length ms
var timeOut = 10000;
// Interval ms
var timeGap = 1000;
var currentTime = (new Date()).getTime();
var endTime = (new Date()).getTime() + timeOut;
var guiTimer = $("#clock");
var running = true;
var timeOutAlert = $("#timeout-alert");
timeOutAlert.hide();
var updateTimer = function() {
// Run till timeout
if(currentTime + timeGap < endTime) {
setTimeout( updateTimer, timeGap );
}
// Countdown if running
if(running) {
currentTime += timeGap;
if(currentTime >= endTime) { // if its over
guiTimer.css("color","red");
}
}
// Update Gui
var time = new Date();
time.setTime(endTime - currentTime);
var minutes = time.getMinutes();
var seconds = time.getSeconds();
guiTimer.html((minutes < 10 ? '0' : '') + minutes + ':' + (seconds < 10 ? '0' : '') + seconds);
if (parseInt(guiTimer.html().substr(3)) <= 10){ // alert the user that he is running out of time
guiTimer.css('color','red');
timeOutAlert.show();
}
};
var pause = function() {
running = false;
};
var resume = function() {
running = true;
};
var start = function(timeout) {
timeOut = timeout;
currentTime = (new Date()).getTime();
endTime = (new Date()).getTime() + timeOut;
updateTimer();
};
return {
pause: pause,
resume: resume,
start: start
};
})(jQuery);
jQuery('#break').on('click',countDown.pause);
jQuery('#continue').on('click',countDown.resume);
var seconds = 60; // seconds we want to count down
countDown.start(seconds*1000);
I tried to fix it but I dont know where/how to put localStorage.
This may help you.
HTML Code:
<div id="divCounter"></div>
JS Code
var test = 60;
if (localStorage.getItem("counter")) {
if (localStorage.getItem("counter") <= 0) {
var value = test;
alert(value);
} else {
var value = localStorage.getItem("counter");
}
} else {
var value = test;
}
document.getElementById('divCounter').innerHTML = value;
var counter = function() {
if (value <= 0) {
localStorage.setItem("counter", test);
value = test;
} else {
value = parseInt(value) - 1;
localStorage.setItem("counter", value);
}
document.getElementById('divCounter').innerHTML = value;
};
var interval = setInterval(function() { counter(); }, 1000);

Java Script Calculating and Displaying Idle Time

I'm trying to write with javascript and html how to display the time a user is idle (not moving mouse or pressing keys). While the program can detect mousemovements and key presses, the program for some reason isn't calling the idleTime() method which displays the time in minutes and seconds.
I'm wondering why the method isn't getting called, as if it is called it would display true or false if a button is pressed.
var startIdle = new Date().getTime();
var mouseMoved = false;
var buttonPressed = false;
function idleTime() {
document.write(buttonPressed);
if (mouseMoved || buttonPressed) {
startIdle = new Date().getTime();
}
document.getElementById('idle').innerHTML = calculateMin(startIdle) + " minutes: " + calculateSec(startIdle) + " seconds";
var t = setTimeout(function() {
idleTime()
}, 500);
}
function calculateSec(startIdle1) {
var currentIdle = new Date().getTime();
var timeDiff = Math.abs(currentIdle - startIdle1);
var idleSec = Math.ceil(timeDiff / (1000));
return idleSec % 60;
}
function calculateMin(startIdle1) {
var currentIdle = new Date().getTime();
var timeDiff = Math.abs(currentIdle - startIdle1);
var idleMin = Math.ceil(timeDiff / (1000 * 60));
return idleMin;
}
var timer;
// mousemove code
var stoppedElement = document.getElementById("stopped");
function mouseStopped() { // the actual function that is called
mouseMoved = false;
stoppedElement.innerHTML = "Mouse stopped";
}
window.addEventListener("mousemove", function() {
mouseMoved = true;
stoppedElement.innerHTML = "Mouse moving";
clearTimeout(timer);
timer = setTimeout(mouseStopped, 300);
});
//keypress code
var keysElement = document.getElementById('keyPressed');
window.addEventListener("keyup", function() {
buttonPressed = false;
keysElement.innerHTML = "Keys not Pressed";
clearTimeout(timer);
timer = setTimeout("keysPressed", 300);
});
window.addEventListener("keydown", function() {
buttonPressed = true;
keysElement.innerHTML = "Keys Pressed";
clearTimeout(timer);
timer = setTimeout("keyPressed", 300);
});
function checkTime(i) {
if (i < 10) {
i = "0" + i
}; // add zero in front of numbers < 10
return i;
}
Here is the HTML code:
<body onload="idleTime()">
<div id="stopped"><br>Mouse stopped</br></div>
<div id="keyPressed"> Keys not Pressed</div>
<strong>
<div id="header"><br>Time Idle:</br>
</div>
<div id="idle"></div>
</strong>
</body>
Actually the keysElement and stoppedElement were not referred firing before the DOM load. and also removed the document.write
Thats all all good. :)
var startIdle = new Date().getTime();
var mouseMoved = false;
var buttonPressed = false;
function idleTime() {
//document.write(buttonPressed);
if (mouseMoved || buttonPressed) {
startIdle = new Date().getTime();
}
document.getElementById('idle').innerHTML = calculateMin(startIdle) + " minutes: " + calculateSec(startIdle) + " seconds";
var t = setTimeout(function() {
idleTime()
}, 500);
}
function calculateSec(startIdle1) {
var currentIdle = new Date().getTime();
var timeDiff = Math.abs(currentIdle - startIdle1);
var idleSec = Math.ceil(timeDiff / (1000));
return idleSec % 60;
}
function calculateMin(startIdle1) {
var currentIdle = new Date().getTime();
var timeDiff = Math.abs(currentIdle - startIdle1);
var idleMin = Math.ceil(timeDiff / (1000 * 60));
return idleMin;
}
var timer;
// mousemove code
//var stoppedElement = document.getElementById("stopped");
function mouseStopped() { // the actual function that is called
mouseMoved = false;
document.getElementById("stopped").innerHTML = "Mouse stopped";
}
function keyStopped() { // the actual function that is called
buttonPressed = false;
document.getElementById("keyPressed").innerHTML = "Keys stopped";
}
window.addEventListener("mousemove", function() {
mouseMoved = true;
document.getElementById("stopped").innerHTML = "Mouse moving";
clearTimeout(timer);
timer = setTimeout(mouseStopped, 500);
});
window.addEventListener("keyup", function() {
buttonPressed = true;
document.getElementById('keyPressed').innerHTML = "Keys Pressed";
clearTimeout(timer);
timer = setTimeout(keyStopped, 500);
});
window.addEventListener("keydown", function() {
buttonPressed = true;
document.getElementById('keyPressed').innerHTML = "Keys Pressed";
clearTimeout(timer);
timer = setTimeout(keyStopped, 500);
});
function checkTime(i) {
if (i < 10) {
i = "0" + i
}; // add zero in front of numbers < 10
return i;
}
window.onload = idleTime;
<div id="stopped"><br>Mouse stopped</br></div>
<div id="keyPressed"> Keys not Pressed</div>
<strong>
<div id="header"><br>Time Idle:</br></div>
<div id="idle"></div>
</strong>

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

Body Background Image Rotation should support dynamic number of images

I have used jquery slideshow to rotate background images. But what my requirement is, I have to display background images according to the specific days. I mean some times I have to rotate one image, some times 3, and some times morethan 3 like this. For this one I have to change the script everytime. How can I rotate background images dynamically without changing my script. If anyone have solution plz suggest me some sample script.
var slideshowSpeed = 6000;
var photos = [
{image1.png},
{image2.png},
{image3.png}
];
$(document).ready(function() {
$("#back").click(function() {
stopAnimation();
navigate("back");
});
$("#next").click(function() {
stopAnimation();
navigate("next");
});
var interval;
$("#control").toggle(function() {
stopAnimation();
}, function() {
$(this).css({"background-image":"url(images/btn_pause.png)"});
navigate("next");
interval = setInterval(function() {
navigate("next");
}, slideshowSpeed);
});
var activeContainer = 1;
var currentImg = 0;
var animating = false;
var navigate = function(direction) {
if (animating) {
return;
}
if (direction == "next") {
currentImg++;
if (currentImg == photos.length + 1) {
currentImg = 1;
}
} else {
currentImg--;
if (currentImg == 0) {
currentImg = photos.length;
}
}
var currentContainer = activeContainer;
if (activeContainer == 1) {
activeContainer = 2;
} else {
activeContainer = 1;
}
showImage(photos[currentImg - 1], currentContainer, activeContainer);
};
var currentZindex = -1;
var showImage = function(photoObject, currentContainer, activeContainer) {
animating = true;
currentZindex--;
$("#headerimg" + activeContainer).css({"background-image":"url(images/" + photoObject.image + ")","display":"block","z-index":currentZindex});
$("#headertxt").css({"display":"none"});
$("#firstline").html(photoObject.firstline);
$("#secondline").attr("href", photoObject.url).html(photoObject.secondline);
$("#pictureduri").attr("href", photoObject.url).html(photoObject.title);
$("#headerimg" + currentContainer).fadeOut(function() {
setTimeout(function() {
$("#headertxt").css({"display":"block"});
animating = false;
}, 500);
});
};
var stopAnimation = function() {
$("#control").css({"background-image":"url(images/btn_play.png)"});
clearInterval(interval);
};
navigate("next");
interval = setInterval(function() {
navigate("next");
}, slideshowSpeed);
});
I'm having the above script.And below is my html
<div id="headerimgs">
<div id="headerimg1" class="headerimg"></div>
<div id="headerimg2" class="headerimg"></div>
<div id="headerimg3" class="headerimg"></div>
</div>
You can make a simple javascript function which returns the var photos based on the current date.
function getPhotos() {
var currentDate = new Date(),
photos;
if (currentDate === new Date("December 25, 2012")) {
photos = [{ .... }];
}
return photos;
}
And your code will be:
var photos = getPhotos();
you can use
var d = new Date();
var n = d.getDay();
to find which day it is .. And for image rotation I would recommend raphael library. This is compatible in most of the browsers ( Firefox 3.0+, Safari 3.0+, Chrome 5.0+, Opera 9.5+ and Internet Explorer 6.0+ ) and very easy to use.

Categories