How to manage multiple timers in javascript? - javascript

Below is the coding I use for one count up timer:
var sec = 0;
function pad ( val ) { return val > 9 ? val : "0" + val; }
function setTime()
{
document.getElementById("seconds0").innerHTML=pad(++sec%60);
document.getElementById("minutes0").innerHTML=pad(parseInt(sec/60,10));
}
var timer = setInterval(setTime, 1000);
If I have two timers, I write like this:
var sec = 0;
var sec1 = 0;
function pad ( val ) { return val > 9 ? val : "0" + val; }
function setTime()
{
document.getElementById("seconds0").innerHTML=pad(++sec%60);
document.getElementById("minutes0").innerHTML=pad(parseInt(sec/60,10));
}
function setTime1()
{
document.getElementById("seconds1").innerHTML=pad(++sec1%60);
document.getElementById("minutes1").innerHTML=pad(parseInt(sec1/60,10));
}
var timer = setInterval(setTime, 1000);
var timer1 = setInterval(setTime1, 1000);
Actually the timer I use is to show waiting time of people. The number of people is a unknown variable. Means that it can be from 1 - 100. So, one people is one timer. Below is the function I written.
showWait = function(){
var html = "";
for (var i = 0; i < total; i++)
{
html += '<div id="numbers" class="col-sm-3 col-xs-6">'+i+'</div>';
html += '<div id="qtime" class="col-sm-3 col-xs-6"></span><div><span class="glyphicon glyphicon-time"></span> Waiting</div><div id="waittime"><label id="minutes'+i+'">00</label>:<label id="seconds'+i+'">00</label></div></div>';
html += '</div>';
}
$('#waitnumber').html(html);
}
So, I don't think the way to create more timer is to keep repeating same function over and over again, right? It can't be if 100 people then there is 100 timers, right? Is there any simpler way to manage multiple timers?

i guess that every interval has 1000 ms waiting time, so you dont need multiple timers just one and in this one timer do what you need for every person
var sec = [time0, time1, time2 ....];
function pad ( val ) { return val > 9 ? val : "0" + val; }
function setTime()
{
for(person = 0; person < numberOfPeople; person++)
{
document.getElementById("seconds" + person).innerHTML=pad(++sec[person]%60);
document.getElementById("minutes" + person).innerHTML=pad(parseInt(sec[person]/60,10));
}
}
var timer = setInterval(setTime, 1000);

IF your time interval for each person is going to be fixed then I would suggest you should run only one timer of 1000ms and define certain variables for each person i.e something like that
var persons = [
{id : 0, min : 0, sec : 0, othercounts: 0},
{id : 1, min : 0, sec : 0, othercounts: 0}
]
and on the execution of timer function, just iterate through the array or (any data structure that you feel comfortable with) and increment the time counter variables for every person and refresh the dom.
your timer function will be like:
function setTime(){
persons.forEach(function(p){
p.min ++;
// your logic
document.getElementById("seconds"+ e.id).innerHTML=pad(++sec%60);
document.getElementById("minutes" + e.id).innerHTML=pad(parseInt(sec/60,10));
});
}
and register the interval only once i.e on document load event or on your custom event
var timer = setInterval(setTime, 1000);
on arrival of new person, just push the person object into the persons array.
This is just one way, there can be more better solution by rendering the html only once at the end of the loop.

Related

How to do a countdown with randomized time intervals, stopping at zero?

i would like to add another counter in this code:
function animateValue(id) {
var obj = document.getElementById(id);
var counter = getLocalStoregaValue();
var current = counter ? +counter : obj.innerHTML;
obj.innerHTML = counter;
setInterval(function() {
var counter = current--;
obj.innerHTML = counter;
localStorage.setItem('counter', counter);
}, 1000);
}
function getLocalStoregaValue() {
return localStorage.getItem('counter');
}
animateValue('value');
I would like it to scale once every second (as in this case) and once every 5 seconds. How can I? And then, how can I make it stop at 0? So without negative numbers. Thank you very much.
EDIT: I explained myself wrong.
I would like a single counter that drops in number from a minimum of 10 to a maximum of 20.
Example: the counter marks 50. After 15 seconds it marks 49. After 18 seconds it marks 48. After 11 seconds it marks 47. And so up to 0.
I hope I explained myself well this time :)
Ok, I was interrupted while posting my answer. Here now the explanation:
I left out the localStorage part of your question and concentrated on the generation of "independent countdowns" first:
function cntdwn(sel,stp,intv){
let el=document.querySelector(sel),
n=el.textContent-stp,
cd=setInterval(()=>{
el.textContent=n;
if((n-=stp)<0) clearInterval(cd);
}, intv);
}
cntdwn('#one',1,1000) ;
setTimeout(()=>cntdwn('#two',1,3000), 12000);
<p>first countdown:<br>step: 1, interval: 1s</p>
<p id="one">15</p>
<p>second countdown:<br>step: 1, action after: 15, 18, 21, 24 ... s (as mentioned in comment)</p>
<p id="two">50</p>
The cntdwn() function provides a scope in which individual countdowns can be set up for arbitrary DOM elements, each with their own counter (it starts with the value found in the DOM element), step-width and interval (in milliseconds).
Each countdown is generated with let cd=setInterval(...). The reference cd can then be used to stop the countdown (in clearInterval(cd)), once the value of n is found to be below zero.
Edit:
Assuming you made a typo in your sequence of intervals and you really meant: 15, 18, 21 seconds, then the edited second countdown should be the correct solution.
I used a setTimeout() function to delay the action by 12 seconds, then, after the first of the regular 3 second intervals (i. e. after a total of 15 seconds) the first change occurs. The countdown then continues in 3 second intervals until it reaches zero.
Yet another edit:
Ok, so you want: "A countdown with random time intervals (range 10 to 20s each) that will stop at zero"
This should do it:
function cntdwn(sel,int1,int2){
let el=document.querySelector(sel),
n=el.textContent-1,
cd=()=>setTimeout(()=>{
el.textContent=n;
if(n--) cd();
}, 1000*(int1+Math.random()*(int2-int1)));
cd();
}
cntdwn('#one',10,20);
<p>countdown:<br>step: 1, intervals: between 10 and 20 s</p>
<p id="one">5</p>
If you can use ES2017, you can use an asynchronous function to do it, like this:
async function animateValue(id) {
function timeout(t){
return new Promise(r => setTimeout(r, t))
}
var obj = document.getElementById(id);
var counter = getLocalStoregaValue();
for(let i = +counter || +obj.innerHTML || 0; i >= 0; i--){
obj.innerHTML = i;
localStorage.setItem('counter', i);
await timeout((Math.random() * 10 + 10) * 1000); //Pause for 10 to 20 seconds. For an integer second value, wrap `Math.random() * 10` into a `Math.floor` call
};
}
function getLocalStoregaValue() {
return localStorage.getItem('counter');
}
animateValue('value').catch(console.error);
<div id="value">50</div>
Try it (I commented out the localStorage part, as it isn't allowed in Stack Snippets):
async function animateValue(id) {
function timeout(t){
return new Promise(r => setTimeout(r, t))
}
var obj = document.getElementById(id);
var counter = getLocalStoregaValue();
for(let i = +counter || +obj.innerHTML || 0; i >= 0; i--){
obj.innerHTML = i;
//localStorage.setItem('counter', i);
await timeout((Math.random() * 10 + 10) * 1000); //Pause for 10 to 20 seconds. For an integer second value, wrap `Math.random() * 10` into a `Math.floor` call
};
}
function getLocalStoregaValue() {
//return localStorage.getItem('counter');
}
animateValue('value').catch(console.error);
<div id="value">50</div>

How do I delay this code running in JavaScript?

I have written this code to change an image:
change = function(){
for (r=0; r<6; r++){
for (i = 0; i < 6 ; i++) {
setInterval(imgfile(number=i+1), 5000);
}
}
}
imgfile= function(number){
a = 'document.getElementById("imgdiv").src = "images/'+number+'.svg"';
eval(a);
}
The function change() is called when a button is clicked.
When I press the button the image changes straight to 6.svg, when I want it to go through the images 1, 2, 3, 4, 5, 6 and to repeat it 6 times. When I change setInterval to change.setInterval or imgfile.setInterval it doesn't work at all. How do I fix this?
change = function(i=0){
imgfile(i%6+1);//change image
if(i<36) setTimeout(change,5000,i+1);//next image in 5 seconds
}
imgfile= function(number){
document.getElementById("imgdiv").src = "images/"+number+".svg";//no need to use ev(i||a)l
}
Instead of loop/interval mess you can simply start a timeout that restarts itself after changing the image... This code will loop over 6 images with a delay of 5 seconds and that 6 times...
Something like this, perhaps?
var index, imgCount, loopCount, imgTag, countdown;
index = 0;
imgCount = 6;
loopCount = 6;
imgTag = document.getElementById('imgdiv');
countdown = function () {
if (index < imgCount * loopCount) {
imgTag.src = 'images/' + index % imgCount + '.svg';
index = index + 1;
setTimeout(countdown, 5000);
}
};
countdown();
Here we're avoiding the double loop and using modular math (index % imgCount) to get the right file number.
For another question I wrote a nice utility function that has quite a number of uses, but can also handle this scenario very easily. The main issue is that there is no time elapsing between the different delays being set. So you are setting 6 different actions to all happen within 5000ms, and all will occur at the same moment.
Here's my original answer
Here's the utility function for that answer, along with its application to your problem.
function doHeavyTask(params) {
var totalMillisAllotted = params.totalMillisAllotted;
var totalTasks = params.totalTasks;
var tasksPerTick = params.tasksPerTick;
var tasksCompleted = 0;
var totalTicks = Math.ceil(totalTasks / tasksPerTick);
var initialDelay = params.initialDelay;
var interval = null;
if (totalTicks === 0) return;
var doTick = function() {
var totalByEndOfTick = Math.min(tasksCompleted + tasksPerTick, totalTasks);
do {
params.task(tasksCompleted++);
} while(tasksCompleted < totalByEndOfTick);
if (tasksCompleted >= totalTasks) clearInterval(interval);
};
// Tick once immediately, and then as many times as needed using setInterval
if (!initialDelay) doTick();
if (tasksCompleted < totalTicks) interval = setInterval(doTick, totalMillisAllotted / totalTicks);
}
// Do 6 actions over the course of 5000 x 6 milliseconds
doHeavyTask({
totalMillisAllotted: 5000 * 6,
totalTasks: 6,
tasksPerTick: 1,
initialDelay: false, // Controls if the 1st tick should occur immediately
task: function(n) { console.log('Set image to "images/' + (n + 1) + '.svg"'); }
});
You want to do setTimeout().
setTimeout pauses for the millesecond value and then does the code. Where setInterval runs the code every whatever milleseconds.
Yeah, don't do change.setInterval or whatever, it is just setInterval.
An example for you would be this inside the for loop to replace the setInterval function.
setTimeout(imgfile(i+1), 5000);

Get variable and count from 0

Forgive me if this sounds a little confusing ... I am trying to adjust the value of a progress bar based on my randomize variable.
var randomize = Math.round(Math.random() * (3000 - 2000) + 1000);
How do I then get javascript to count from 0 to 'randomize' in seconds, so that I can apply it to my progress bar?
You could do something like this:
var randomize = Math.round(Math.random() * (3000 - 2000) + 1000);
var counter = 0;
var timer = setInterval( function(){
if ( counter <= randomize ){
// update progress bar
counter += 1;
}else{
clearInterval( timer );
}
}, 1000 );
Basically what I'm doing here is setting up a function to be called every second ( 1000 = 1 second in JavaScript). The timer will check if the counter variable has reached the value of randomize and if not, it will increment it's value by one.
Once counter is equal to randomize, the timer will be cleared.
References -
setInterval()
clearInterval()
var seconds = 0;
var timer = setInterval(function() {
seconds = seconds + 1;
if (seconds == randomize) {
clearInterval(timer);
}
}, 1000);

How to use setInterval in an slightly irregular pattern such as in a for loop?

The behaviour I want is this: The background color changes to say, gold, and remains that color for say X length of time. Then, background color changes to say, red, and remains that color for say Y length of time. The background color then changes back to gold and remains that color for X length of time. Then the background color changes back to red and stays that way for Y length of time. This whole kit and caboodle executes in a loop-style fashion for Z number of times and then ends.
I've tried putting setInterval'd functions into a for loop (in order to count the number of times we make the change) but have found that all of the functions that have been set to setInterval themselves all start running the interval timers at the same time (not in sequence).
I hope this is clear. Here is a JSFiddle of my efforts: http://jsfiddle.net/6WE6s/3/ I've managed to get the background color to change in a even pattern, but I want the pattern described above and I'm confused as to what to do next.
Thanks in advance for the help! :)
var colors = [
['gold', 2000], // X = 2000 miliseconds
['red', 1000] // Y = 1000
],
repeat = 3, // Z = 3,
index = 0, // current position in colors array
changeColor = function( ) {
// if index == colors.length then mod = 0
var mod = index % colors.length;
if(!index || mod || --repeat ) {
index = mod;
var data = colors[ index++ ]; // data = [ currentColor, currentColorTimeout ]
document.body.style.background = data[0];
setTimeout( changeColor, data[1] ); // and so on
}
//if index >0 && index == last
//then decrement `repeat` and check if is == 0
//nothing to do :)
};
changeColor(); // run
This is a simple example. You can make function with arguments(colors,repeats) and its body as above.
Note:
setInterval isn't suitable for this purpose because in setInterval you pass timeout once
If repeat initially is 0 will be an infinite number of repetitions
Don't use setInterval(). With setTimeout() you can do something like this:
function changeColors(colors, repeats) {
var i = 0;
if (typeof repeats === "undefined")
repeats = 1;
function doNext() {
if (i >= colors.length){
if (--repeats > 0)
i = 0;
else
return;
}
$('body').css('background-color', colors[i].color);
setTimeout(doNext, colors[i++].delay);
}
doNext();
}
changeColors([{color : "gold", delay : 2000},
{color : "red", delay : 4000}],
3);
You can add as many colours as you like, each with their own delay, by adding more elements to the array you pass to changeColors(). The function will go through the colours in turn, and do the whole sequence the number of times specified in the repeats parameter.
Demo: http://jsfiddle.net/nnnnnn/6WE6s/10/
Here's my effort - no jQuery required:
function colorCycle(el, count, cols) {
var i = 0,
n = cols.length;
// allow this to work on any element given its ID
el = (typeof el === "string") ? document.getElementById(el) : el;
if (n === 0) {
return; // no colours?
} else if (n === 1) {
count = 1; // don't trigger any timers if there's only one colour
}
// all of the hard work is done here
(function repeat() {
var interval = cols[i][1];
el.style.backgroundColor = cols[i][0];
// only do the whole cycle "count" times - 0 = forever
if (++i === n) {
if (count && !--count) {
return;
}
i = 0;
}
setTimeout(repeat, interval); // call myself
})(); // IIFE starts the cycle straight away
};
colorCycle(document.body, 5, [
['red', 1000],
['gold', 500]]);
See http://jsfiddle.net/alnitak/42PeT/
Abstain from using setInterval. Reference here.
EDIT: I've missed the different delay in calls.
var colors = ["#FF0000", "#00FF00", "#0000FF"];
var times = [1000, 2000, 3000];
var backgroundColor = "";
var counter = 0;
var changeBackground = function () {
// if we ran out of colors — do nothing: this simply goes out
// of the function, without continually calling setTimeout.
if (counter >= colors.length)
return;
// you fetch your new color here and increase the counter
// The counter keeps count of how many animations you've done.
backgroundColor = colors[counter];
// increase the counter to point to the next index of colors
// array you'll use in a subsequent call
counter++;
// do your magic voodoo change background animation here.
// I'm just doing a console.log() to be sure this works.
// Your question was framework agnostic, the answer should be too.
console.log(backgroundColor);
// setInterval to repeat
window.setTimeout(changeBackground, times[counter]);
}
window.setTimeout(changeBackground, times[counter]);
try this
var colors = [];
colors.push({color:"gold", time:4000}); //4000 X length of time
colors.push({color:"red", time:2000}); //2000 Y length of time
var numberofTimes = 50; //50 Z number of times
var $body;
var times = 0; // counter for tracking
var currentColor = {}; //currentColor info can be used to get the current
$(function(){
$body = $('body');
changeBG();
});
function changeBG()
{
currentColor = colors[times % colors.length];
$body.css('background-color',currentColor.color);
times++;
if(times<numberofTimes)
setTimeout(changeBG, currentColor.time);
}
check this quick DEMO
A basic example iterating an array of color and time arrays with setTimeout.
(function() {
var i = 0,
colorsTimes = [['gold', 'red', 'gold', 'red', 'gold'],
[2000, 4000, 2000, 4000, 2000]];
function switchColors() {
setTimeout(function() {
$('body').css('background-color', colorsTimes[0][i]);
if (++i < colorsTimes[0].length) switchColors();
}, colorsTimes[1][i]);
}
switchColors();
}());
Fiddle
Using setTimeout:
var doCount = (function() {
var count = 0;
var interval;
var limit = 5; // default
return function(num) {
limit = num || limit;
if (count < limit) {
count++;
console.log('running number ' + count);
interval = setTimeout(arguments.callee, 1000);
} else {
interval && clearTimeout(interval);
}
}
}())
Using setInterval:
var doCount = (function() {
var count = 0;
var interval;
var limit = 5; // default
return function(num) {
limit = num || limit;
if (interval) {
if (++count >= limit) {
interval && clearInterval(interval);
}
console.log('running number ' + count);
} else {
interval = setInterval(arguments.callee, 1000);
}
}
}())
The advantage of setTimeout is that you can adjust the time between runs to make it more regular, setInterval just tries to run as regularly as it can.

Increment integer by 1; every 1 second

My aim is to create identify a piece of code that increments a number by 1, every 1 second:
We shall call our base number indexVariable, I then want to: indexVariable = indexVariable + 1 every 1 second; until my indexVariable has reached 360 - then I wish it to reset to 1 and carry out the loop again.
How would this be possible in Javascript? - if it makes a difference I am using the Raphael framework.
I have carried out research of JavaScript timing events and the Raphael delay function - but these do not seem to be the answer - can anyone assist?
You can use setInterval() for that reason.
var i = 1;
var interval = setInterval( increment, 1000);
function increment(){
i = i % 360 + 1;
}
edit: the code for your your followup-question:
var interval = setInterval( rotate, 1000);
function rotate(){
percentArrow.rotate(1,150,150);
}
I'm not entirely sure, how your rotate works, but you may have to store the degrees in a var and increment those var too like in the example above.
var indexVariable = 0;
setInterval(function () {
indexVariable = ++indexVariable % 360 + 1; // SET { 1-360 }
}, 1000);
Try:
var indexVariable = 0;
setInterval(
function () {
indexVariable = (indexVariable + 1) % 361;
}, 1000}

Categories

Resources