Javascript - few intervals in right order - javascript

In my code I have three intervals which should be executed random times one after the another.
var times = Math.floor((Math.random() * 3) + 2);
var turn = 0;
var schemaInterval1 = setInterval(function(){
console.log('first');
turn++;
if(turn == times)
{
times = Math.floor((Math.random() * 3) + 2);
turn = 0;
clearInterval(schemaInterval1);
}
},1000);
var schemaInterval2 = setInterval(function(){
console.log('second');
turn++;
if(turn == times)
{
times = Math.floor((Math.random() * 3) + 2);
turn = 0;
clearInterval(schemaInterval2);
}
},1000);
var schemaInterval3 = setInterval(function(){
console.log('third');
turn++;
if(turn == times)
{
times = Math.floor((Math.random() * 3) + 2);
turn = 0;
clearInterval(schemaInterval3);
}
},1000);
After each execution of the code within interval, I add 1 to the turn value. When turn and times values are equal I reset both of them. Leave currently working interval and skip to another one. But unfortunately they don't work in correct order and in my console I get that message:
first
second
third
first
second
first
(4)second
How can I rewrite my code to put those intervals in proper order and don't allow others work until first finish it's task?

You start your intervals all at the same time. If you want to run them in series, you have to start one when you clear the previous one.
This code should do what you are looking for:
var times = Math.floor((Math.random() * 3) + 2);
var turn = 0;
var intervalNumber = 1;
var intervalTime = 1000;
var numberOfIntervals = 3;
function instantiateInterval() {
if (intervalNumber <= numberOfIntervals) {
console.log('Timer number: ' + intervalNumber);
var interval = setInterval(function() {
turn++;
if(turn === times) {
times = Math.floor((Math.random() * 3) + 2);
turn = 0;
clearInterval(interval);
instantiateInterval();
}
}, intervalTime);
intervalNumber++;
}
}
instantiateInterval();

Related

how to spawn 1 to 3 objects randomly many times Javascript

I am trying to spawn 1 to 3 monsters randomly many times in Javascript, this is the code i have for now but this only makes it randomly spawn when i refresh and then it keeps spawning the same amount of monsters the whole time.
function spawnMonster(){
setInterval(function(){
for(var i = 0; i < randomMonster; i++){
monsterDiv.innerHTML += monsterPic;
outputDiv.innerHTML = "monstrene angriper.</br>" + outputDiv.innerHTML;
}
}, Math.floor(Math.random()* 3000) + 1000);
}
I'm assuming randomMonster is the random value between 1-3.
When the variable is set, it (obviously) doesn't change as you did describe.
Just make sure you calculate a new randomMonster -value inside the setInterval function:
function spawnMonster(){
setInterval(function(){
const randomMonster = Math.floor(Math.random() * 3) + 1;
for(var i = 0; i < randomMonster; i++){
monsterDiv.innerHTML += monsterPic;
outputDiv.innerHTML = "monstrene angriper.</br>" + outputDiv.innerHTML;
}
}, Math.floor(Math.random() * 3000) + 1000);
}

How change variable from function setTimeout inside an loop

How alternate value to variable dinamic_delay using conditions described below?
var emails = []; // array
var number = 5;
var count = 0;
var dinamic_delay;
for (i = 0; i < emails.length; i++) {
count++;
if (count == number) {
dinamic_delay = 3000;
count = 0; // resset count
} else {
dinamic_delay = 500;
}
setTimeout(function (i) {
sendemail(email[i]);
}, dinamic_delay * i, i);
}
I had to remind myself how setTimeout works:
a. setTimeout(myfunction(), 5000) -calls the function after at least 5000 millisecs from now (when this code is executed)
b. setTimeout(myfunction(), 5000) -calls the function after at least 5000 millisecs from now (when this code is executed)
in other words there is not an automatic 10,000 millisec before b is called, e.g. might by 6000 ms
setInterval is useful if you want to call things at regular intervals.
The example below displays console.log message 3, 3, 3, 3, 10 seconds & repeats until the final email.
const bigDelay_c = 10000; //secs
const smallDelay_c = 3000; //secs
const totalEmails_c = 18; //total to process
var totalEmailsProcessed = 0; //running total
var timerId = 0;
timerId = setInterval(alertFunc, smallDelay_c);
function alertFunc() {
//sendEmail logic here
var currentdate = new Date();
totalEmailsProcessed++;
console.log(totalEmailsProcessed, currentdate.getHours() + ":" +
currentdate.getMinutes() + ":" + currentdate.getSeconds());
clearInterval(timerId); //stop interval repeating
//stop if all emails have been processed
if (totalEmailsProcessed >= totalEmails_c) {
console.log('all emails processed');
return;
}
//5th item in every 5 get bigDelay_c
if (totalEmailsProcessed % 5 == 4)
timerId = setInterval(alertFunc, bigDelay_c);
else
timerId = setInterval(alertFunc, smallDelay_c);
}

Modify Countup Timer To Include Currency Formatting In Javascript

I have a simple countup timer that takes a starting number and randomly counts up. However, it doesn't work correctly on numbers that include decimals and commas.
How can I modify this to count up correctly in cents?
For example I want to count starting at the number 1,234,567.15 and every 500 milliseconds it adds a random amount of cents to the end. Then when it goes over 99 it adds to the dollar value.
Current Usage:
<span>$</span><span id="counter">1,234,567.15</span>
Javascript:
<script>
var timer;
function startCount() {
timer = setInterval(count, 500); // 200 = 200ms delay between counter changes. Lower num = faster, Bigger = slower.
}
function count() {
var do_wait = Math.ceil(4 * Math.random());
if (do_wait == 4) {
var rand_no = Math.ceil(4 * Math.random()); // 4 = random decrement amount. Counter will decrease anywhere from 1 - 4.
var el = document.getElementById('counter');
var currentNumber = parseFloat(el.innerHTML);
var newNumber = currentNumber + rand_no;
if (newNumber < 99999999999) {
el.innerHTML = newNumber;
}
}
}
startCount();
</script>
parseFloat doesn't process ',' ,it will stop parse will met ',';
the best way is to use newNumber.toLocaleString()
var timer;
function startCount() {
timer = setInterval(count, 500); // 200 = 200ms delay between counter changes. Lower num = faster, Bigger = slower.
}
function count() {
var do_wait = Math.ceil(4 * Math.random());
if (do_wait == 4) {
// var rand_no = Math.ceil(4 * Math.random()); // 4 = random decrement amount. Counter will decrease anywhere from 1 - 4.
var rand_no = 4 * Math.random(); //if you also want cents change,take this and comment previous line
var el = document.getElementById('counter');
var currentNumber = parseFloat(el.innerHTML.replace(/,/g, ''));
var newNumber = currentNumber + rand_no;
if (newNumber < 99999999999) {
el.innerHTML = Number(newNumber.toFixed(2)).toLocaleString();
}
}
}
startCount();
<span>$</span><span id="counter">1,234,567.15</span>
if not work ,process it manually:
replace ',' to '' and calculate the number and add ',' back:
var timer;
function startCount() {
timer = setInterval(count, 500); // 200 = 200ms delay between counter changes. Lower num = faster, Bigger = slower.
}
function count() {
var do_wait = Math.ceil(4 * Math.random());
if (do_wait == 4) {
// var rand_no = Math.ceil(4 * Math.random()); // 4 = random decrement amount. Counter will decrease anywhere from 1 - 4.
var rand_no = 4 * Math.random(); //if you also want cents change,take this and comment previous line
var el = document.getElementById('counter');
var currentNumber = parseFloat(el.innerHTML.replace(/,/g, ''));
var newNumber = currentNumber + rand_no;
if (newNumber < 99999999999) {
el.innerHTML = processNumber(newNumber);
}
}
function processNumber(num) {
let strArr = num.toFixed(2).split('.')[0].split(/|/g).reverse();
let result = strArr.map(function(v, index) {
return index % 3 === 0 ? v + ',' : v;
}).reverse();
return result.join('').replace(/,$/, '.') + num.toFixed(2).split('.')[1];
}
}
startCount();
<span>$</span><span id="counter">1,234,567.15</span>

Trying to get timer to start once arrived on the page

I made the following fiddle of what I have right now..
https://jsfiddle.net/r5yj99bs/1/
I'm trying to start right when I get onto a page, but allowing the option to leave the pause/resume option. Then is there anyway to display the remaining time as '5 minutes' instead of '300 seconds' and then count down that way rather than only seconds.
<button class="start-pause">Start</button>
<h2 class="time-left"></h2>
var times = [];
var counter_interval;
var $time_left = $('.time-left');
var $button = $('.start-pause');
// timer length in seconds
var timer_length = 300;
$('body').on('click', '.start-pause', function() {
// are we starting or stopping?
var starting = times.length % 2 == 0;
times.push(Date.now());
if (starting) {
$button.html('Pause');
counter_interval = setInterval(function() {
var time_left = Math.floor(timer_length - sum_elapsed());
if (time_left < 1) {
clearInterval(counter_interval);
return finished();
}
$time_left.html(time_left);
}, 100);
} else {
$button.html('Resume');
clearInterval(counter_interval);
}
});
var sum_elapsed = function() {
sum = 0;
for (var i=0; i<times.length; i++) {
if (i % 2 == 1) {
sum += (times[i] - times[i-1]);
}
if (i == (times.length - 1)) {
sum += (Date.now() - times[i]);
}
}
// convert milliseconds to seconds
return sum / 1000;
};
var finished = function() {
$button.attr('disabled','disabled').html('Finished');
$time_left.html("Time's Up");
};
There is a good time module called moment. You can get it through npm or from moments.com
That can format relative time to human readable strings.
If you want to do it yourself, take the seconds modulus 60 to get the minutes. Using modulus you can extract all info about hours and so on.
You may change the following line:
$time_left.html(time_left);
to:
$time_left.html(secToMinTxt(time_left));
and add the following functions:
function pad(num) {
var str = "" + num;
var pad = "00";
return pad.substring(0, pad.length - str.length) + str;
}
function secToMinTxt(seconds) {
var min = Math.floor(seconds / 60);
var sec = seconds % 60;
return pad(min) + ":" + pad(sec);
}
JSFiddle reference : https://jsfiddle.net/r5yj99bs/2/
If interpret Question correctly, try using Math.round with argument existing time_left variable divided by 60
var time_left = Math.round(Math.floor(timer_length - sum_elapsed()) / 60);
jsfiddle https://jsfiddle.net/r5yj99bs/3/

Howto run function every few seconds that has return values?

How can I run this every few second , without blocking the rest of the pagefrom loading.
function Create() {
var SomeArray = [];
for ( var i=0; i<=1 ; i ++) {
SomeArray[i] = (Math.random() * 10) + 1;
//alert(arr[0]);
}
return SomeArray;
}
var x = Create();
alert(x[0] + x[1]);
I was trying this var timer = setInterval(Create, 5000); it prevent loading rest of the page.
i want to get new values every few seconds
A basic example would be:
var counter = 0;
var timerRef;
var increment = function() {
counter += 1;
console.log(counter);
timerRef = setTimeout(increment, 1000);
}
setTimeout(increment, 1000);
// clearTimeout(timerRef);
Please avoid document.write refer the screencast for further details.
setInterval() can be configured to repeatedly call any function you designate at whatever time interval you request. But, you can't retrieve a return value from that function. Instead, you need to process the results from within the callback that you pass to setInterval() or call some other function and pass the results you generate inside the callback. This is how asynchronous functions work in JavaScript. I've provided several examples below of your options:
If you just want to generate two random decimal values between 1 and 10 (inclusive) every 5 seconds, you can do that like this:
var interval = setInterval(function() {
var rand1 = (Math.random() * 10) + 1;
var rand2 = (Math.random() * 10) + 1;
// now insert code here to do something with the two random numbers
}, 5000);
If you wanted the random values to be integers (which is more common), then you would do this:
var interval = setInterval(function() {
var rand1 = Math.floor(Math.random() * 10) + 1;
var rand2 = Math.floor(Math.random() * 10) + 1;
// now insert code here to do something with the two random numbers
}, 5000);
If you want to call a function and pass it those two random numbers, you can do this:
function processRandoms(r1, r2) {
// code here to do something with the two random numbers
}
var interval = setInterval(function() {
var rand1 = Math.floor(Math.random() * 10) + 1;
var rand2 = Math.floor(Math.random() * 10) + 1;
processRandoms(rand1, rand2);
}, 5000);
You can then stop the recurring interval at any time with this:
clearInterval(interval);

Categories

Resources