Timeout longer after every repetition - javascript

I'm trying to make a function that plays a sound effect and replaces image on site with an image from array after a certain delay (currentTime). The delay is is supposed to get longer after every repetition until time of all repetitions (maxTime) passes 20000 miliseconds (about 20 reps).
In current layout the site freezes. I tried to move calculation of currentTime, maxTime, and tabIndicator out of Timeout, but then the delay is always 2000 miliseconds(which is time lenght of the last rep). Any advice?
function roll()
{
var maxTime=0;
var currentTime=0;
var addValue=100;
var tabIndicator=0;
while(maxTime<=20000)
{
window.setTimeout(function(){
currentTime = currentTime + addValue;
maxTime = maxTime + currentTime;
music();
document.getElementById("write").innerHTML += (currentTime + "<br>" + maxTime + "<br>" + addValue + "<br><br>");
tabIndicator++;
if(tabIndicator == 9){ tabIndicator = 0; }
},currentTime)
}
}

Try this.
function roll()
{
var maxTime=0;
var currentTime=0;
var addValue=100;
var tabIndicator=0;
var playMusic = function()
{
window.setTimeout(function(){
currentTime = currentTime + addValue;
maxTime = maxTime + currentTime;
music();
document.getElementById("write").innerHTML += (currentTime + "<br>" + maxTime + "<br>" + addValue + "<br><br>");
tabIndicator++;
if(tabIndicator == 9){ tabIndicator = 0; }
if (maxTime <= 20000)
playMusic();
},currentTime);
};
playMusic();
}

Related

How to do when 'countdown timer' has run out and then run the function 'alert()' in 'Momentjs'

Here I use Codeigniter and MomentJS, How to run the 'alert()' function when 'contdown timer' has run out
in Main.JS
var timeEvent = <?=$timeEvent?>;
var timeNow = <?=now('America/Santiago')?>;
var diff = timeEvent - timeNow;
var duration = moment.duration(diff*1000, 'milliseconds');
var interval = 1000;
setInterval(function(){
duration = moment.duration(duration - interval, 'milliseconds');
$('#result').text(duration.hours() + ":" + duration.minutes() + ":" + duration.seconds());
}, interval);
Surely it's this simple no?
setInterval(function(){
duration = moment.duration(duration - interval, 'milliseconds');
if( duration <= 0 ) {
alert("Done");
}
$('#result').text(duration.hours() + ":" + duration.minutes() + ":" + duration.seconds());
}, interval);

How to toggle setInterval on click javascript

I want to be able to toggle setInterval on click.
Here is my code that start the interval:
var clock = document.querySelector('#hexTime');
var hexClock = document.querySelector('#hexClock');
function run() {
var time = new Date();
var hours = (time.getHours() % 12).toString();
var minutes = time.getMinutes().toString();
var seconds = time.getSeconds().toString();
if(hours.length < 2) {
hours = '0' + hours;
}
if(minutes.length < 2) {
minutes = '0' + minutes;
}
if(seconds.length < 2) {
seconds = '0' + seconds;
}
var clockStr = hours + ' : ' + minutes + ' : ' + seconds;
var hexStr = '#' + hours + minutes + seconds;
clock.textContent = clockStr;
hexClock.textContent = hexStr;
document.body.style.backgroundColor = hexStr;
}
run();
setInterval(run, 1000);
How can I acheive that?
First, add an element (preferably a button) that will listen for the click, give it an ID like:
<button id="myToggleButton">CLICK ME</button>
Then add an event listener for that element and set or clear interval when it's clicked like:
var clock = document.querySelector('#hexTime');
var hexClock = document.querySelector('#hexClock');
function run() {
var time = new Date();
var hours = (time.getHours() % 12).toString();
var minutes = time.getMinutes().toString();
var seconds = time.getSeconds().toString();
if(hours.length < 2) {
hours = '0' + hours;
}
if(minutes.length < 2) {
minutes = '0' + minutes;
}
if(seconds.length < 2) {
seconds = '0' + seconds;
}
var clockStr = hours + ' : ' + minutes + ' : ' + seconds;
var hexStr = '#' + hours + minutes + seconds;
clock.textContent = clockStr;
hexClock.textContent = hexStr;
document.body.style.backgroundColor = hexStr;
}
var myButton = document.querySelector('#myToggleButton');
// this will hold the information about the interval
var myInterval = null;
// the event listener for the click event
myButton.addEventListener("click", function(){
if(myInterval){ // if we have an interval (myInterval != null)
clearInterval(myInterval); // clear it
myInterval = null; // make it null again
}
else{ // if we don't have an interval (myIntervall == null)
myInterval = setInterval(run, 1000); // start one
}
});
// if you don't want the interval to start by default then remove the next line
myInterval = setInterval(run, 1000);

javascript manual countdown timer (based on the user input)

i want to make a countdown timer for a project in which the countdown start when the user inputs some time in 00:00:00 h-m-s format, i have written some code which is half correct and i'm lost what to do next
// Wait for user to click the button before reading the value
window.onload=function(){
var work = document.getElementById("dl");
work.addEventListener("click", handler);
}
function handler() {
//taking user input
var time1 = document.getElementById('hms').value;
//splitting it to seperate variables
var pieces = time1.split(":");
var hours = pieces[0];
var minutes = pieces[1];
var seconds = pieces[2];
//just calculating total number of seconds
seconds = seconds + minutes*60 + hours*3600;
var tot = seconds + minutes*60 + hours*3600;
// Save the interval's handle to `timer`
var timer = setInterval(countdown, 1000);
function countdown() {
var container = document.getElementById('count');
var counter = 0, k=1, j=1, i=0, s1= pieces[2];
//loop to print the timer
for(i=0; i<tot; i++){
if(seconds>0){
counter ++ ;
if(counter==60*k){
minutes--;
k++;
}
if(counter==3600*j){
hours--;
j++;
}
container.innerHTML = 'Please wait <b>' + hours + '</b> hours, <b>' + minutes + '</b> minutes, <b>' + seconds + '</b> seconds';
}//end of if
else {
container.innerHTML = 'Time over';
clearInterval(timer);
}
}
/* seconds--;
if (seconds > 0) {
container.innerHTML = 'Please wait <b>' + seconds + '</b> seconds..';
} else {
container.innerHTML = 'Time over';
clearInterval(timer);
} */
}
}
<input type="text" id="hms" placeholder="enter in the format 00:00:00 " />
<input type="button" id="dl" value="Start" />
<div id="count"></div>
i know i have made this complicated, can someone please make it simple? it will be a great help, thanks!
I have modified the function handler.You can try this.
function handler() {
//taking user input
var time1 = document.getElementById('hms').value;
//splitting it to seperate variables
var pieces = time1.split(":");
var hours = pieces[0];
var minutes = pieces[1];
var seconds = pieces[2];
var time = {
hours: hours * 1,
minutes: minutes * 1,
seconds: seconds * 1
};
// Save the interval's handle to `timer`
var timer = setInterval(countdown, 1000);
function countdown() {
var container = document.getElementById('count');
if (time.seconds > 0) {
time.seconds--;
}
else {
if (time.minutes > 0) {
time.minutes--;
time.seconds = 60;
}
else {
time.minutes = 60;
time.seconds = 60;
time.hours--;
}
}
if (time.hours >= 0) {
container.innerHTML = 'Please wait <b>' + time.hours + '</b> hours, <b>' + time.minutes + '</b> minutes, <b>' + time.seconds + '</b> seconds';
}
else {
container.innerHTML = 'Time over';
clearInterval(timer);
}
}
}

Daily countdown timer - Display Message at 21:57

I'm struggling to figure out how Date() works, I found this on the web and wanted to make a countdown that stops at 21:57 UTC Time. It currently displays the message at 21:00 and apears until 22:00.
I tried to add if(currenthours != 21 && currentminutes >= 57){ and always broke it and got the message. I want it to stop 3 minutes before 22:00 and display the message. After it gets to 22:00 restart the countdown for the next day at 21:57.
Any help will be greatly appreciated !
var date;
var display = document.getElementById('time');
setInterval(function(){
date = new Date( );
var currenthours = date.getUTCHours();
// alert(currenthours);
var currentminutes = date.getUTCMinutes();
// alert(currentminutes);
var hours;
var minutes;
var secondes;
if (currenthours != 21) {
if (currenthours < 21) {
hours = 20 - currenthours;
} else {
hours = 21 + (24 - currenthours);
}
minutes = 60 - date.getUTCMinutes();
secondes = 60 - date.getUTCSeconds();
display.innerHTML = ('00' + hours).slice(-2) + ' HOURS ' + '<p>' +
('00' + minutes).slice(-2) + ' MINUTES ' + '</p>' +
('00' + secondes).slice(-2) + ' SECONDS';
} else {
display.innerHTML = "IT'S 21:57";
}
},1000);
<div id='time'></div>
Made a fiddle
https://jsfiddle.net/5qrs0tcp/1/
This is what I ended up with :
/*
|================================|
| COUNTDOWN TIMER |
|================================|
*/
// Return the UTC time component of a date in h:mm:ss.sss format
if (!Date.prototype.toISOTime) {
Date.prototype.toISOTime = function() {
return this.getUTCHours() + ':' +
('0' + this.getUTCMinutes()).slice(-2) + ':' +
('0' + this.getUTCSeconds()).slice(-2);
}
}
// Return the difference in time between two dates
// in h:mm:ss.sss format
if (!Date.prototype.timeDiff) {
Date.prototype.timeDiff = function(date2) {
var diff = Math.abs(this - date2);
return timeobj = {
hours : (diff/3.6e6|0), // hours
minutes : ('0' + ((diff%3.6e6)/6e4|0)).slice(-2), // minutes
seconds : ('0' + ((diff%6e4)/1e3|0)).slice(-2) // seconds
}
}
}
function countDown() {
var now = new Date();
var limitHr = 19;
var limitMin = 55;
var limitDate = new Date(+now);
// Set limitDate to next limit time
limitDate.setUTCHours(limitHr, limitMin, 0, 0);
// var msg = ['Currently: ' + now.toISOTime() + '<br>' + 'Limit: ' + limitDate.toISOTime()];
var msg = [];
var diff;
// If outside limitHr:limitMin to (limitHr + 1):00
if (now.getUTCHours() == limitHr && now.getUTCMinutes() >= limitMin) {
msg.push('Countdown stopped');
setTimeout(function(){
msg = ['Wait for it'];
var jsonCounter = {
stats : msg
}
jsonfile.writeFileSync(DailyGamePath, jsonCounter, {spaces: 3});
},5000);
var jsonCounter = {
stats : msg
}
jsonfile.writeFileSync(DailyGamePath, jsonCounter, {spaces: 3});
} else {
if (now > limitDate) limitDate.setDate(limitDate.getDate() + 1);
var jsonCounter = {
hours : now.timeDiff(limitDate).hours,
minutes : now.timeDiff(limitDate).minutes,
seconds : now.timeDiff(limitDate).seconds,
validating : msg
}
jsonfile.writeFileSync(DailyGamePath, jsonCounter, {spaces: 3});
}
}
setInterval(countDown, 1000);
var daily_status;
setTimeout( function(){
setInterval( function() {
jsonfile.readFile(DailyGamePath, (err, obj) => {
daily_status={
hours: obj.hours,
minutes: obj.minutes,
seconds: obj.seconds,
stats: obj.stats,
validating: obj.validating
};
return daily_status;
});
}, 1000);
}, 3000);
setTimeout( function(){
io.sockets.on('connection', (socket) => {
setInterval( function() {
// var GameStatus=DailyGameStatus();
socket.broadcast.emit('stream', {hours:daily_status.hours, minutes:daily_status.minutes, seconds:daily_status.seconds, stats:daily_status.stats, validating:daily_status.validating});
}, 1000);
});
}, 3000);
Date objects are very simple, they're just a time value and some handy methods.
I think your logic just needs to be:
if (currenthours != 21 && currentminutes < 57) {
// set the out of hours message
} else {
// time is from 21:57 to 21:59 inclusive
}
The countdown doesn't quite work because you're counting to 00 not to 57, but otherwise there doesn't seem to be an issue.
var date;
var display = document.getElementById('time');
setInterval(function(){
date = new Date( );
var currenthours = date.getUTCHours();
var currentminutes = date.getUTCMinutes();
var hours;
var minutes;
var secondes;
var limitHr = 5; // Change these to required values
var limitMin = 02; // Using 5:12 for convenience
var message = 'Currently: ' + date.toISOString() + '<p>';
// Create new message if outside limitHr:limitMin to limitHr:59 inclusive
if (currenthours != limitHr || currentminutes < limitMin) {
if (currenthours <= limitHr) {
hours = limitHr - currenthours;
} else {
hours = limitHr + (24 - currenthours);
}
minutes = limitMin - date.getUTCMinutes();
minutes += minutes < 0? 60 : 0;
secondes = 60 - date.getUTCSeconds();
message += ('00' + hours).slice(-2) + ' HOURS ' + '<p>' +
('00' + minutes).slice(-2) + ' MINUTES ' + '</p>' +
('00' + secondes).slice(-2) + ' SECONDS';
} else {
message += 'It\'s on or after ' + limitHr + ':' +
('0'+limitMin).slice(-2) + ' GMT';
}
// Display the message
display.innerHTML = message;
},1000);
<div id="time"></div>
Yes, the timer has issues but that wasn't part of the question. For a counter, it's simpler to just work in time differences, so I've added some methods to Date.prototype for ISO time (to be consistent with ISO Date) and time difference, then use those functions.
The function builds a Date for the end time so that calculations can use Date methods.
// Return the UTC time component of a date in h:mm:ss.sss format
if (!Date.prototype.toISOTime) {
Date.prototype.toISOTime = function() {
return this.getUTCHours() + ':' +
('0' + this.getUTCMinutes()).slice(-2) + ':' +
('0' + this.getUTCSeconds()).slice(-2) + '.' +
('00' + this.getUTCMilliseconds()).slice(-3) + 'Z';
}
}
// Return the difference in time between two dates
// in h:mm:ss.sss format
if (!Date.prototype.timeDiff) {
Date.prototype.timeDiff = function(date2) {
var diff = Math.abs(this - date2);
var sign = this > date2? '+' : '-';
return sign + (diff/3.6e6|0) + ':' + // hours
('0' + ((diff%3.6e6)/6e4|0)).slice(-2) + ':' + // minutes
('0' + ((diff%6e4)/1e3|0)).slice(-2) + '.' + // seconds
('00' + (diff%1e3)).slice(-3); // milliseconds
}
}
function countDown() {
var now = new Date();
var limitHr = 1;
var limitMin = 10;
var limitDate = new Date(+now);
// Set limitDate to next limit time
limitDate.setUTCHours(limitHr, limitMin, 0, 0);
var msg = ['Currently: ' + now.toISOTime() + '<br>' + 'Limit: ' + limitDate.toISOTime()];
var diff;
// If outside limitHr:limitMin to (limitHr + 1):00
if (now.getUTCHours() != limitHr || now.getUTCMinutes() != limitMin) {
if (now > limitDate) limitDate.setDate(limitDate.getDate() + 1);
msg.push(now.timeDiff(limitDate));
} else {
msg.push('It\'s after ' + limitHr + ':' + ('0'+limitMin).slice(-2));
}
document.getElementById('msgDiv2').innerHTML = msg.join('<br>');
}
window.onload = function() {
setInterval(countDown, 1000);
}
<div id="msgDiv2"></div>>
I've left the milliseconds in, round to seconds if you wish.
I've left the timer using setInterval, though I'd prefer to use setTimeout and manually calculate the time to just after the next full second so that it never skips. Most browsers using setTimeout will slowly drift so that they skip a second every now and then. Not really an issue unless you happen to see it, or compare it to the tick of the system clock.

Synchronization of two timers (setInterval)

I'm working in an script which contains a function that needs to be called at every 10 minutes. Also, to inform the user of how many time is left before reloading of the function (via AJAX, but this is not relevant now), I put a little regressive timer.
This is the main structure:
$(document).ready(function () {
// Test's function
function loadDate() {
var myDate = new Date();
$("#dateload").html(myDate);
};
// Startup Variables
countermin = 10; // 10 minutes
countersec = 60;
minpass = 0;
secpass = 0
// Showing info before timer.
$("#reloadtime").html("Function will be reloaded in " + countermin + "m<b>" + (60 - countersec) + "</b>s<br/>(countersec's value: " + countersec + " - secpass' value: " + secpass + ")");
$("#timescalled").text("The date function has been called " + minpass + " times after page's load.");
loadDate();
// FIRST setInterval
// It's our timer.
intvl1 = setInterval(function () {
if (countersec++ == 60) {
countermin--;
countersec = 1;
}
if (countermin < 0) {
countermin = 9;
countersec = 1;
secpass = 0;
}
secpass++;
$("#reloadtime").html("Function will be reloaded in " + countermin + "m<b>" + (60 - countersec) + "</b>s<br/>(countersec's value: " + countersec + " - secpass' value: " + secpass + ")");
}, 1000);
// SECOND setInterval
// Counting 10 minutes to execute the function again (and again...).
intvl2 = setInterval(function () {
minpass++;
$("#minpass").text("The date function has been called " + minpass + " times after page's load.");
loadDate();
}, 600000);
});
My problem is: both timers are not synchronized. The intvl2 is executing the function and going back before the timer (intvl1) reaches 0. The error is about 20 seconds, increasing after each 10 minutes.
If you compare with the time printed on beginning, around 6, 7 minutes of execution you can see difference with in the times, when comparing with your PC's clock.
How can I get them synchronized?
You can check this fiddle.
A simpler approach would be to use a single timer that does both things, updates the countdown information and triggers the event. Below is an example:
var oneSecond = 1000;
var counter = 0;
var eventInterval = 5 * oneSecond;
var timesTriggered = 0;
setInterval(function () {
counter = (counter + oneSecond) % eventInterval;
$('.countdown').text((eventInterval - counter) / oneSecond);
if(counter == 0){
timesTriggered++;
$('.timesTriggered').text(timesTriggered);
}
}, oneSecond);
Working fiddle: http://jsfiddle.net/TFDSU/3/
I've hacked about with your code a bit - I can't sit through a 10 minute countdown :) so I switched it to a minute and some other changes but this is working fine and not losing time..
$(document).ready(function () {
// Function of Test
function loadDate() {
var myDate = new Date();
$("#dateload").html(myDate);
};
countersec = 60; //
minpass = 0;
$("#reloadtime").html("Function will be reloaded in "+countersec+"</b>s<br/>");
$("#timescalled").text("The date function has been called " + minpass + " times after page's load.");
loadDate();
intvl1 = setInterval(function () {
countersec--;
if (!countersec) { countersec=60; }
$("#reloadtime").html("Function will be reloaded in "+countersec+"</b>");
}, 1000);
intvl2 = setInterval(function () {
minpass++;
$("#minpass").text("The date function has been called " + minpass + " times after page's load.");
loadDate();
}, 60000);
});

Categories

Resources