pause an interval along a chain - javascript

I know this isn't going to help you understand so I'll break it down.
I have a webpage that has an interval for the time, this time is translated into an hour and that loads a audio file. The problem being that the interval reloads the audio every second and I only want it to interval based on the hour and the clock to work as intended. I have it set up like this.
The basic of it is that I have a page loading stuff based on the time of day and I need a way to edit the time live with some function and change the elements. If there is a better way to do this, I am open to suggestions.
note: i can not use jquery
//interval//
var myVar = setInterval(function(){ myTimer() }, 1000);
//get the time//
function myTimer() {
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
var time = h + ":" + m + ":" + s;
document.getElementById('time').innerHTML = time;
mod_time(h,m,s)
}
// mod the time //
function mod_time(h,m,s) {
var x = 0;
if(x == 1){
var h = h - h + 2
}
if(x == 2){
var h = h - h + 3
}
else{
var h = h;
}
//applying just the hours//
apply_mod_time(h)
//displaying the full modded time for debugging//
var t_str = h + ":" + m + ":" + s;
document.getElementById('time2').innerHTML = t_str;
}
//playing sound based on the hour//
function apply_mod_time(h) {
if (h==1) {
document.getElementById("myAudio").src = "moo.mp3";
}
}

Add another variable that specifies the current hour. When you execute the interval every second, see if h !== hourVariable. If they do not match, load the audio file and update the hourVariable to equal h.

Related

Updating the button element as a countdown timer through javascript

I want to create a countdown timer which looks like an fps counter for webpage...
after hours of time spent i m not able to find out what is wrong.....help
<script>
var myvar = setInterval(function () { startTimer() }, 1000);
function startTimer() {
var presentTime = 17 + ":" + 00;
var timeArray = presentTime.split(/[:]+/);
var m = timeArray[0];
var s = checkSecond((timeArray[1] - 1));
if (s == 59) {
m = m - 1
}
//if(m<0){alert('timer completed')}
var button2 = document.createElement("Button2");
var interval = m + s;
button2.innerHTML = Math.round(interval);
button2.style = "top:0; left:0rem; height:10% ;color: black; background-color: #ffffff;position:fixed;padding:20px;font-size:large;font-weight: bold;";
setTimeout(startTimer, 1000);
document.body.appendChild(button2);
}
function checkSecond(sec) {
if (sec < 10 && sec >= 0) {
sec = "0" + sec
}; // add zero in front of numbers < 10
if (sec < 0) {
sec = "59"
};
return sec;
}
</script>
I can find three errors that hinder your code from performing correctly.
Multiple timers
First off since you invoke both a setInterval in outer scope, and then a setTimeout after each performed iteration, you will end up getting many unwanted timer instances that will do some crazy counting for you.
I recommend you to scrap either one of these and stick with just one of them.
For my example i happend to stick with the setInterval since you're executing the very same method over and over any way.
The initialization
Since the presentTime is declared inside the startTimer-function it will be constantly overwritten with 17 + ":" + 00 (resulting in "17:0" btw).
This is solved by declaring it in the outer scope instead.
Remembering the changes
Finally you need to save the current state of presentTime after modifications. Just adding a presentTime = [m,s].join(":"); at the end of startTimer() solves this.
var presentTime = "17:00";
function startTimer() {
var timeArray = presentTime.split(/[:]+/);
var m = timeArray[0];
var s = checkSecond((timeArray[1] - 1));
if (s == 59) {
m = m - 1
}
var button2 = document.createElement("Button2");
var interval = s;
button2.innerHTML = m + ":" + s;
button2.style = "top:0; left:0rem; height:10% ;color: black; background-color: #ffffff;position:fixed;padding:20px;font-size:large;font-weight: bold;";
document.body.appendChild(button2);
presentTime = [m,s].join(":");
}
function checkSecond(sec) {
if (sec < 10 && sec >= 0) {
sec = "0" + sec
}; // add zero in front of numbers < 10
if (sec < 0) {
sec = "59"
};
return sec;
}
var interval = setInterval(startTimer, 1000);

Clock not updating every second using moment.js

First time using moment.js and I am struggling to implement a clock to show the time in CET and PST. My code is as follows:
function cetClock() {
var cet = moment.tz("Europe/London");
var today = new Date(cet);
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkCetTime(m);
s = checkCetTime(s);
$rootScope.cetTime = h + ":" + m + ":" + s;
var t = setTimeout(cetClock, 300);
}
function checkCetTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
cetClock()
<div class="col-md-6">
<p>CET: {{$root.cetTime}}</p>
</div>
The issue I have is that the time in the view is only being updated every 4-5 seconds. If I log the h, m, s within the function, it shows every 500 milliseconds the time being updated.
Question
Why is the clock in the viiew failing to update every second?
I suggest using $timeout instead of setTimeout which will automatically trigger a digest cycle.

Issue with JavaScript-based countdown clock

I'm trying to make a JavaScript countdown clock that starts from 1 hour all the way down.
I'm using just a bit of jQuery in the process.
$(document).ready(function(){
var h,m,s,output;
$("#StartW").click(function(){
function startWork()
{
h = 1;
m = 0;
s = 0;
output = h + ":" + m + ":" + s;
setInterval(function() {count()}, 1000);
}
function count()
{
if(s == 0)
{
if(m == 0)
{
if(h == 0);
{
output = "time's up";
}
h = 0;
m = 59;
s = 59;
}
m = m - 1;
s = 59;
}
s = s - 1;
output = h + ":" + m + ":" + s;
document.getElementById("WTM").innerHTML = output;
}
});
});
1- StartW is the id of the button calling the function.
2- WMT is the id of the span where the clock will be displayed.
When I click the button, I get no results. Nothing happens. The JavaScript Console in my navigator doesn't indicate any errors at all.
Actually, at pressing that button you don't call any function, you just initiate them. Get outside from click event the functions count and startWork, and do stuff like
$('#StartW').on( 'click', startWork );
Check it here
In your click event function, you declare two functions, but never call them, so nothing happens. Try this:
$(document).ready(function(){
var h,m,s,output;
$("#StartW").click(function(){
function startWork()
{
h = 1;
m = 0;
s = 0;
output = h + ":" + m + ":" + s;
setInterval(function() {count()}, 1000);
}
function count()
{
if(s == 0)
{
if(m == 0)
{
if(h == 0)
{
output = "time's up";
}
h = 0;
m = 59;
s = 59;
}
m = m - 1;
s = 59;
}
s = s - 1;
output = h + ":" + m + ":" + s;
document.getElementById("WTM").innerHTML = output;
}
startWork();
});
});
Fixing indentation made it super clear, also there is a ; on the line if(h == 0); that should be removed
As a note for your way to count one hour, you need to understand that it might not be very accurate. You ask the code to wait for 1000 milliseconds to add 1 second yourself, exactly like we do to count seconds saying "mississipi" to help us wait for the next second. Although JavaScript is more precise at counting 1000Milliseconds in 1 sec as we are to say mississipi in exactly one second, it might be off for X and Y reasons. The only real accurate way to know how long has elapsed is to watch the clock, and look at it again and again until it shows that we waited an hour. So, in JS, save the time when it started, every second or so display the remaining time by the difference of the current time and started time and display the timer.

how to create a javascript countdown which on refreshing continues counting

I try it with javascript and jquery but no idea how to do that. i wont to let the timer not begins on refreshing counting again. It´s same as an auction when he counting down 3,2 and on refreshing he don´t begins again it should continue count down where it last ended. And on other products it must count from 3 again. Have anyboy an idea?
Edit: because some users missunderstood what i am searching for.
my issue is that i don´t know how to save the time when someone refresh the page to continue to count it down. if someone refresh the site at 21sec and he or she have 30 secs to make there choice. and after refreshing the site, the counter will count at 21sec down and not started again by 30sec again.
no ajax.
When possible hardcoded.
And if not possible then the cookie variant.
You can set a name to your window on load of the page. Before setting the name check whether this window already has a name.
if it doesn't have a name, set a name to the window and start counting at 0 and save the count value in a cookie each time it increment.
if it does have a name(that means page is reloaded), read the count value from the cookie and do the increment and save to cookie.
EDIT: Example, Call initCount() function on body load. Use decrementAndSave function to decrement the value of the count and save it to cookie.
var count = 3;// 3 -> 2 -> 1
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
function initCount() {
if (window.name) {
count = getCookie("count_" + window.name);// to keep separate count cookies for each window
} else {
window.name = "w_" + (new Date().getTime());
count = 3;
setCookie("count_" + window.name, count, null);
}
}
function decrementAndSave() {
count--;
// separate cookie for each window or tab
setCookie("count_" + window.name, count, null);
}
It's not Perfect but I designed this script to do a 30min countdown and then to change some text during the last few seconds. The only issue with it is that when it gets to 1:00 it starts at 30:60 and I haven't figured out how to fix that yet. This may not work perfectly for what your looking for but it might put you on the right path.
<script>
//add leading zeros
setInterval(function() {
function addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
var x = document.getElementById("timer");
var d = new Date();
var s = (d.getSeconds());
var m = (d.getMinutes());
var a = addZero(30 - m);
var b = addZero(60 - m);
var c = (60 - s);
var z = "<span style='color:red;font-size:50px;'>" + "Break" + "</span>";
var v = "<span style='color:black;font-size:24px;'>" + "Break" + "</span>";
//Decide how much should be subtracted from the time
if (m > 30) {
y = b;
}
else if (m < 30) {
y = a;
}
//elements for changing text
if (y < 2 && c < 15) {
q = z;
}
else {
q = v;
}
var t = y + (":" + addZero(c) + " Till Station " + (q));
x.innerHTML = t;
}, 250);
</script>
<div align="center" id="timer" style='color:black;font-size:24px;' ></div>
If you have a countdown, then you must have some sort of end time defined. So instead of having a countdown and just subtracting 1 every second, try something like this:
var endTime = new Date(2011,11,13,0,0,0); // Midnight of December 13th 2011
var timer = setInterval(function() {
var now = new Date();
var timeleft = Math.max(0,Math.floor((endTime.getTime()-now.getTime())/1000));
var d, h, m, s;
s = timeleft % 60;
timeleft = Math.floor(timeleft/60);
m = timeleft % 60;
timeleft = Math.floor(timeleft/60);
h = timeleft % 24;
timeleft = Math.floor(timeleft/24);
d = timeleft;
document.getElementById('counter').innerHTML = "Time left: "+d+" days, "+h+" hours, "+m+" minutes, "+s+" seconds.";
if( timeleft == 0) clearInterval(timer);
},1000);
var interval = 90000; //90 secounds
function reset() {
localStorage.endTime = +new Date() + interval;
}
if (!localStorage.endTime) {
reset();
}
function millisToMinutesAndSeconds(millis) {
var minutes = Math.floor(millis / 60000);
var seconds = ((millis % 60000) / 1000).toFixed(0);
return minutes + ":" + (seconds < 10 ? "0" : "") + seconds;
}
setInterval(function () {
var remaining = localStorage.endTime - new Date();
if (remaining >= 0) {
document.getElementById("tooltip").innerText =
millisToMinutesAndSeconds(remaining);
} else {
reset();
}
}, 100);

Javascript : Manipulating the status bar to display the date?

I'm trying to write a script to display the current time on a page every minute on the status bar. However nothing shows up on the bar and I have no idea what is wrong.
function display_time(){
var d = new Date();
var h = d.getHours(); // Extract hours
var m = d.getMinutes(); // Extract minutes
var ampm = (h >= 12)?"PM":"AM" // Convert to 12 hr format
if (h > 12) h -= 12; // Next 4 lines; convert time to 12hr format
if (h==0) h = 12;
if (m < 10) m = "0" + m;
var t = h + ':' + m + ' ' + ampm;
defaultStatus = t;
// Repeat function every minute
setTimeout('display_time()', 60000);
}
And Finally I call it as the page loads with <body onload= 'display_time();'>
The time however doesn't show in the status bar of any browser. Any thoughts?
Use window.status instead of defaultStatus. But please be aware that you can't change the status bar in some browsers.

Categories