Jquery progress bar that work with respect to time - javascript

I need a progress that works with time ... for example: If I give start time and end time, then progress bar works with that time.
Example:
start_time = 3:30 pm
end_time = 4:10 pm
total_time = end_time - start_time
And progress bar should complete with respect to total_time and also total time is must in minutes. I have trying this plugin.
But its not work much for me...

This is what I would give to you as a direction, it updates only once a minute so if you don't see the progressbar moving wait for it :) Fiddle
HTML
<div id="prbar"><span id="fill"></span>
</div><span id="showleftmin"></span>
CSS
#prbar {
width:100px;
border:1px solid black;
height: 10px;
}
#fill {
width:0px;
background: red;
height: 10px;
display:block;
}
Javascript
var start = parseInt("2325", 0); //start time
var end = parseInt("2350", 0); //end time
var totalminutes = end - start;
var incrementer = 100/totalminutes;
var lengthprbar = 0;
var minutesleft = totalminutes;
var fill = document.getElementById('fill');
setInterval(function () {
if (minutesleft === 0) {
return;
}
lengthprbar += incrementer;
fill.style.width = lengthprbar + 'px';
document.getElementById('showleftmin').innerHTML = minutesleft - 1;
minutesleft--;
}, 60000);

Related

how to cancel pop up audio in javascript

hello I'm new to code and javascript I'm creating a clock with timer. the countdown is done well with an alarm and a pop up when the timer reaches zero. only I can't turn off the alarm when I close the pop up it opens in a loop. i need help please
let departInput = document.querySelector('#times');
let subButton = document.querySelector('#sub')
subButton.addEventListener('click', event => {
let temps = (departInput.value)*60;
var timerElement = document.getElementById("MyTimerDisplay")
setInterval(() => {
let minutes = parseInt(temps / 60, 10)
let secondes = parseInt(temps % 60, 10)
minutes = minutes < 10 ? "0" + minutes : minutes
secondes = secondes < 10 ? "0" + secondes : secondes
timerElement.innerText = `${minutes}:${secondes}`
temps = temps <= 0 ? 0 : temps - 1
if(minutes == 0 && secondes == 0){
var snd = new Audio('clock.mp3');
snd.play();
alert("cest l'heure")
}
}, 1000)
});
To address the problem you are having you should call clearTimer() when the alarm rings so that its callback won't be running again and again each second even after the condition to break was met.
Here's a working example to show the point:
let departInput = document.querySelector('#times');
let subButton = document.querySelector('#sub')
subButton.addEventListener('click', event => {
//decides how many minutes before the alarm rings
let minutesToAlarm = parseInt(departInput.value);
//initializes elapsedSeconds
let elapsedSeconds = minutesToAlarm*60;
var timerElement = document.getElementById("MyTimerDisplay");
var myTimer = setInterval(() => {
//converts elapsedSeconds in mm:ss format and refresh the ui
let minutes = Math.floor(elapsedSeconds/60);
let secondes = elapsedSeconds % 60;
timerElement.innerText = `${minutes}:${secondes}`
//decrement elapsedSeconds by 1
elapsedSeconds--;
if(elapsedSeconds === 0){
/*
* Part muted because there's no reference to clock.mp3
*
var snd = new Audio('clock.mp3');
snd.play();
*/
alert("cest l'heure");
//here clears the timer so that the callback
//won't be running again anymore
clearTimeout(myTimer);
}
}
, 1000);
});
#sub{
border: solid 1px black;
min-width: 5em;
padding: 2px;
cursor: pointer;
}
#MyTimerDisplay{
border: dashed 4px darkgray;
margin-top: 5px;
width: fit-content;
padding: 5px 20px;
}
<input id="times" type="text" placeholder="departInput"/>
<button id="sub">clickme</button>
<div id="MyTimerDisplay">#times</div>

Time conditions in javascript

could anyone help me with conditions based on time?
css:
Day {
position: absolute;
width: 360px;
height: 360px;
background-image: url("../image/BackgroundDay.png");
background-repeat: no-repeat;
}
Night {
position: relative;
width: 360px;
height: 360px;
background-image: url("../image/BackgroundNight.png");
background-repeat: no-repeat;
}
html
<img id="Day" alt="" style="opacity: 0;"/>
<img id="Night" alt="" style="opacity: 0;"/>
js
var dayToNight1 = '19:05:00';
var dayToNight2 = '19:05:05';
var dayToNight3 = '19:05:10';
var dayToNight4 = '19:05:15';
var dayToNight5 = '19:05:20';
var dayToNight6 = '19:05:25';
var dayToNight7 = '19:05:30';
var dayToNight8 = '19:05:35';
var dayToNight9 = '19:05:40';
var dayToNight10 = '19:05"45';
if(time > dayToNight1)
{
document.getElementById("Day").style.opacity = "0.9";
document.getElementById("Night").style.opacity = "0.1";
} // i got these conditions 10, I just didnt add them so it is not that long.
var nightToDay1 = '08:00:00';
var nightToDay2 = '08:00:05';
var nightToDay3 = '08:00:10';
var nightToDay4 = '08:00:15';
var nightToDay5 = '08:00:20';
var nightToDay6 = '08:00:25';
var nightToDay7 = '08:00:30';
var nightToDay8 = '08:00:35';
var nightToDay9 = '08:00:40';
var nightToDay10 = '08:00:45';
if(time > nightToDay1 && time <= '19:05:00')
{
document.getElementById("Day").style.opacity = "0.1";
document.getElementById("Night").style.opacity = "0.9";
}// same here 10 conditions
My problem is. I have two images layered on top of each other.
I would like to change from Day to Night if specific time comes. So if time reaches 19:00:00 I want to slowly change background from Day to Night just using opacity.
Then I will go from Night to Day in 08:00:00. But here comes the problem, I dont know how to make that condition and tell if (time > 19:00:00) start changing opacity for both images and go from Day to Night If time reaches 19:00:00 it just insta blick to the night without my opacity transition.
Could you give me quick idea how to make specific condition on time using javascript please? Thank you for any idea. Or if you have any other idea how to make something like that more effectively I would appreciate that
I think this might get you a little closer to what you need. Instead of specifying times manually, it's easier to find out how far you are between the start and end of the transition, and then use that to set the opacity.
Times are represented here as arrays of [hours, minutes] and we then find how many total minutes there are in each time.
I imagine this isn't quite perfect yet but it should hopefully illustrate what is possible:
const getTotalMinutes = ([hours, minutes]) =>
(hours * 60) + minutes;
const transitionStart = getTotalMinutes([9, 13]);
const transitionEnd = getTotalMinutes([9, 15]);
const getCurrentTransitionState = () => {
const now = new Date();
const totalMinutes = getTotalMinutes([
now.getHours(),
now.getMinutes(),
]);
const transitionTotal = transitionEnd - transitionStart;
const timeIntoTransition = totalMinutes - transitionStart;
if (timeIntoTransition >= transitionTotal) {
return 1;
}
return timeIntoTransition > 0 ?
timeIntoTransition / transitionTotal :
0;
}
setInterval(() => {
const current = getCurrentTransitionState();
document.getElementById('day').style.opacity = 1-current;
}, 1000);
img {
position: fixed;
top: 0;
left: 0;
transition: all 10s ease;
width: 100vw;
}
<img id="night" src="http://sarahstup.com/wp/wp-content/uploads/2017/01/night-time-background.jpg" />
<img id="day" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT-OLKhRVHgSrPFxIY8n7ZmrgpZQFvgxeT7p3DWifbHBKoF1D57zg" />

Javascript div width countdown

I'm trying to visualize a countdown via a div's width. This could be used for something like a banner system showing when the next banner will slide in, or for a notification system showing how long the notification will be visible.
So in my example below, I have the .outer div emptied after 5 seconds, but the .timer div's width is not reaching width: 0%; at the same time as the setTimeout() kicks in.
The variable len would represent how long the banner or notification would be shown for.
The calculation in the variable offset is what is throwing me off (I think), I cannot seem to get the calculation correct. I would like it to be dynamic, meaning, no matter what len is and what the width of the outer/parent div is, it will always take len time to reach width: 0%;.
I hope my explanation makes sense. Any help would be greatly appreciated.
const len = 5000;
let outer = document.querySelector('.outer');
let timer = document.querySelector('.timer');
let timerWidth = timer.offsetWidth;
let offset = len / timerWidth;
let init = 100;
let interval = setInterval(() => {
init = init - offset;
timer.style.width = init + '%';
}, 1000);
setTimeout(() => {
outer.innerHTML = '';
clearInterval(interval);
}, len);
* {
box-sizing:border-box;
}
body {
padding: 100px 10px 10px;
}
.outer {
width: 100%;
border: 1px solid slategray;
padding: 10px;
}
.timer {
width: 100%;
height: 10px;
background: red;
transition: all 1000ms linear;
}
<div class="outer">
<div class="timer"></div>
<p>Some Message Here!</p>
</div>
Two problems with the code:
interval doesn't start as soon as the page is loaded so the CSS is late in transition.
offset was wrong indeed.
Here's how I fixed it:
let toElapse = 3000; // modify as you like
let tick = 1000; //if you modify this don't forget to replicate
//in CSS transition prop
let countDownEl = document.querySelector('#countdown');
let outer = document.querySelector('.outer');
let timer = document.querySelector('.timer');
let init = 100;
// we calculate the offset based on the tick and time to elapse
let offset = init / (toElapse/tick);
countDownEl.innerHTML = init;
setTimeout(()=>{
// we need to start the first CSS transition ASAP so it is not late.
init = init - offset;
timer.style.width = init.toFixed(2) + '%';
},0)
let interval = setInterval(() => {
// the same interval.
countDownEl.innerHTML = init;
init = init - offset;
timer.style.width = init.toFixed(2) + '%';
}, tick);
setTimeout(() => {
// the same clearance timeout
outer.innerHTML = '';
clearInterval(interval);
}, toElapse);
* {
box-sizing:border-box;
}
body {
padding: 100px 10px 10px;
}
.outer {
width: 100%;
border: 1px solid slategray;
padding: 10px;
}
.timer {
width: 100%;
height: 10px;
background: red;
transition: width 1s linear;
}
<div class="outer">
<div class="timer"></div><span id="countdown"></span>
<p>Some Message Here!</p>
</div>
If you use percentage in width you don't need to know the width of your box.
you just need to substract and add on offset to timeout.
const len = 5000;
let outer = document.querySelector('.outer');
let timer = document.querySelector('.timer');
let timerWidth = timer.offsetWidth;
let offset = 100 * 1000 / 5000;
let interval = setInterval(() => {
init = init - 20;
timer.style.width = init + '%';
}, 1000);
setTimeout(() => {
outer.innerHTML = '';
clearInterval(interval);
}, len + 1000);

Qualtrics - progress to next block when time is up

I need a survey to auto progress to the next block when a specified time limit has been reached for the previous block. Currently I am using the below script to display the timer but need the script to execute the action when time has elapsed. Any assistance is greatly appreciated.
Javascript in timing question.
Qualtrics.SurveyEngine.addOnload(function()
{
var headerCont = document.createElement("div");
headerCont.className = "header-cont";
headerCont.id = "header_container";
var header = document.createElement("div");
header.className = "header"
header.id = "header_1";
var timer = document.createElement("div");
timer.className = "timer";
timer.id = "timer_1";
timer.innerHTML = "Time Remaining: <span id='time'>00:10</span>";
headerCont.appendChild(header);
header.appendChild(timer);
document.body.insertBefore(headerCont, document.body.firstChild);
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
var myTimer = setInterval(function() {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
var text = ('innerText' in display)? 'innerText' : 'textContent';
display[text] = minutes + ":" + seconds;
if (--timer < 0) {
clearInterval(myTimer);
timeOver();
}
}, 1000);
}
var timerSeconds = 10,
display = document.querySelector('#time');
startTimer(timerSeconds, display);
var timeOver = function() {
document.getElementById("timer_1").innerHTML = "Time is up.";}
});
CSS
.header-cont {
width:100%;
position:fixed;
top:0px;
z-index:1000;
}
.header {
height:75px;
background:#FFFFFF;
width:100%;
margin:0px auto;
}
.timer{
margin: auto;
text-align: center;
vertical-align: middle;
font-size: 200%;
font-family: Arial;
}
EDITED ANSWER BASED ON COMMENT:
Initialize an embedded data field in the survey flow before block:
blockTimeFlag = 0
Add the following lines to the timeOver function:
Qualtrics.SurveyEngine.setEmbeddedData("blockTimeFlag", "1");
$('NextButton').click();
However, this means that none of your questions can be forced response.
Add display logic to your questions:
if blockTimeFlag = 0

clear interval not stopping at desired point

I looked at some other similar problems on this site and could not fix this problem. Below is part of a pomodoro clock program that I'm making. The problem is that I'm unable to make this set interval method stop when the clock reaches 00:00.
here is my code:
var break_minutes = 0;
var ses_minutes = 0;
var ses_minutes_sec;
var display = document.querySelector('#time');
function increment_ses (id) {
ses_minutes = ses_minutes + 1;
document.getElementById("ses_value").innerHTML = ses_minutes ;
document.getElementById("timmer_circle").innerHTML = ses_minutes;
}
function decrement_ses (id) {
if (ses_minutes > 0) {
ses_minutes = ses_minutes - 10;
} if (ses_minutes < 0) {
ses_minutes = 0;
}
document.getElementById("ses_value").innerHTML = ses_minutes ;
document.getElementById("timmer_circle").innerHTML = ses_minutes;
}
function runTimer () {
var minutes = ses_minutes-1;
var seconds = 10;
var interval = setInterval(function () {
seconds = seconds -1;
if (seconds == 0) {
minutes --;
seconds = 10 -1;
}
function str_pad_left(string,pad,length) {
return (new Array(length+1).join(pad)+string).slice(-length);
}
var finalTime = str_pad_left(minutes,'0',2)+':'+str_pad_left(seconds,'0',2);
document.getElementById("timmer_circle").innerHTML= finalTime;
if (minutes == 0) {
if (seconds == 0) {
return clearInterval(interval);
}
}
},1000);
}
the HTML
<html>
<head>
<title>Pomodoro</title>
<script src="pomodoro.js"></script>
</head>
<body>
<style>
.timmer_circle
{
width: 300px;
height: 300px;
border-radius: 50%;
font-size: 50px;
color: #fff;
line-height: 300px;
text-align: center;
background: #000;
}
.break_length{width:100%;}
#decrement{float:left;width:100px;}
#break_value{text-align: center;padding-left: 100px;}
#increment{margin:0 auto;width:100px;}
.session_length{width:100%; margin-top: 10px;}
#decrement_ses{float:left;width:100px;}
#ses_value{padding-left: 100px;}
#increment_ses{margin:0 auto;width:100px;}
#start_but{margin-top: 20px;}
#pause_but{margin-top: 20px; margin-left: 2px;}
</style>
<table>
<tr>
<td>
<div class = "timmer_circle" id ="timmer_circle" value = ""> <span id = "time">Session</span> </div>
</td>
</tr>
</table>
<div class="session_length">
<button type="button" id = "decrement_ses" onClick = "decrement_ses(this.id);">ses/dec</button>
<button type="button" id = "ses_value" >0</button>
<button type="button" id = "increment_ses" onClick = "increment_ses(this.id);">ses/inc</button>
</div>
<div class="break_length">
<button type="button" id = "decrement" onClick = "decrement_break(this.id);">brk/dec</button>
<button type="button" id = "break_value" value = "" >0</button>
<button type="button" id = "increment" onClick = "increment_break(this.id);">brk/inc</button>
</div>
<button id ="start_but" onClick="runTimer();">START</button>
<button id ="pause_but">PAUSE</button>
</body>
</html>
So, there's a number of issues with your code, specifically how you're calculating seconds and minutes. Seconds are never zero when you hit your case statement the way you're doing it, because you test for zero at the start of your function and then reset them to 10-1.
I would move that check to the start of the function, as part of your initial conditional. There are still other issues, but this is to answer your specific question about the interval. The below code will exit as expected:
var ses_minutes = 1;
var minutes = ses_minutes-1;
var seconds = 10;
var interval = setInterval(function () {
seconds = seconds -1;
if (seconds == 0) {
if(minutes === 0){
return clearInterval(interval);
}
minutes --;
seconds = 10 - 1;
}
function str_pad_left(string,pad,length) {
return (new Array(length+1).join(pad)+string).slice(-length);
}
var finalTime = str_pad_left(minutes,'0',2)+':'+str_pad_left(seconds,'0',2);
document.getElementById("timmer_circle").innerHTML= finalTime;
},1000);
/* EDIT */
So taking a few minutes to think about how I'd do this if it were me, I'd break things up into functions a little differently, and I'd also use setTimeout. I'd also calculate based on elapsed time rather than assuming the interval or timeout tick will happen at exactly 1000ms, since that's not always reliable. The below is probably still not perfect (I've only done cursory testing) but closer to what I'd do if I were tasked with this:
const display = document.getElementById('timer');
const countDownFrom = 15000; // time in milliseconds to count from
let startTime = new Date().getTime();
function padNumber(num){
let str = num.toString();
return str.length > 1 ? str : '0' + str;
}
function getDisplay(milliseconds){
const seconds = milliseconds / 1000;
const displayMinutes = padNumber(Math.floor(seconds / 60));
const displaySeconds = padNumber(Math.floor(seconds % 60));
return displayMinutes + ':' + displaySeconds;
}
function tick(){
const currentTime = new Date().getTime();
const elapsedTime = currentTime - startTime;
// test to see if the timer has expired
if(countDownFrom - elapsedTime <= 0){
display.innerHTML = '00:00';
return;
}
display.innerHTML = getDisplay(countDownFrom - elapsedTime);
setTimeout(tick,1000);
}
display.innerHTML = getDisplay(countDownFrom);
setTimeout(tick, 1000);

Categories

Resources