I'm creating a countdown, which i need to count down it to 0 but in random numbers.
Ex- countdown from 4 minutes by second by second, but i need to show a value between 300 to 390 countdown to 0 with random numbers within above 4 minutes period.
I created random number count down, but still cannot able to figure out how to target that become 0 within given time.
<script>
var count = 350; //this is a random value between(300-390)
var timer = setInterval(function() {
//this will generate number between 0 to 10 and reduce it from count randimly
count -= Math.floor(Math.random()*9);
//set it to html element
jQuery('#maindvpart').html(count);
//when number become 0
if( count <= 0) {
jQuery('#maindvpart').html(0);
count = 0;
clearInterval(timer);
}
//but i need to run this countdown within 4 minutes
//(so when 0 minutes ends above count should zero, until 0 it should count down from random number)
},1000);
</script>
<div id="maindvpart"> </div>
anyone have idea or example how to do this, thank you
Your "timer" runs each second. When you do "count -= Math.floor(Math.random()*9);", it reduces "count" variable value much faster, so you will always reach "count <= 0" much faster than 4 minutes. If you want to run your timer for 4 minutes, you need to run your timer per second - 240 times, and "display a random number", but do not subtract that random number from count. Does this help?
Editing with an example, hoping it would point you towards your goal:
<script>
var count = 240; //4 minutes
var displayNumber = 350; //or whatever number you want to start with
var timer = setInterval(function() {
//this will generate number between 0 to 10 and reduce it from displayNumber randomly
displayNumber -= Math.floor(Math.random()*9);
count--;
console.log(displayNumber);
// exit if either the display number is <= 0 or the time is up
if( displayNumber <= 0 || count <= 0) {
console.log(0);
displayNumber = 0;
clearInterval(timer);
}
},1000);
</script>
Solution 1:
simply modify the time interval after which the random number is reduced by unit step (ie:1) to indicate the time step necessary for the random number to equal 0 when the time is up . the equation would be :
{delay before subtracting 1 from rand# (in sec) = time elapsed till rand# reaches 0 (in sec)/rand#}
ex:
1) rand# = 300 , needed to count down till reaches 0 in 2 minutes (120sec) , then 300 needs to count down by 1 each 120/300 sec
var count = 300 // your randomly generated number;
var time = 60 //time elapsed before the random number to equal 0;
var timer = setInterval(function() {
count = count -1;
console.log(count);
if( count <= 0) {
count = 0;
clearInterval(timer);
}
},(time/count)*1000);
Solution 2:
modify the unit step by which the random number is decreased every second till it reaches 0 after the specified time is elapsed . the equation would be :
{random # decrement step = rand#/time elapsed till rand# reaches 0 (in sec)}
ex:
1) rand# = 300 , needed to count down till reaches 0 in 1 minute (60sec) , then 300 needs to count down by 300/60 each 1 sec
var count = 300 // your randomly generated number;
var time = 20 //time elapsed before the random number to equal 0;
var decrementStep=count/time;
var timer = setInterval(function() {
count = count - decrementStep;
console.log(count);
if( count <= 0) {
count = 0;
clearInterval(timer);
}
},1000);
Related
I found this script from a website. The loop ends when it has followed 40 Instagram accounts at a 2-second interval. How do I modify the script so it waits for 10 minutes before repeating the same loop for 3 times? Basically, it goes:
Follow an account and wait for 2 seconds X40
Wait for 10 minutes
Follow an account and wait for 2 seconds X40
Wait for 10 minutes
Follow an account and wait for two seconds X40
Wait for 10 minutes
---LOOP ENDS---
var TagFollow = document.getElementsByTagName("button");
var SearchFollow = "Follow";
var foundFollow;
function clickfollow(){
for (var i = 0; i < TagFollow.length; i++) {
if (TagFollow[i].textContent == SearchFollow) {
foundFollow = TagFollow[i];
foundFollow.click();
break;
}
}
}
var i = 1;
function myLoop() {
setTimeout(function() {
console.log(new Date().toLocaleTimeString());
clickfollow();
//document.getElementsByTagName("ul")[3].scrollIntoView(false
i++;
if (i < 41) {
myLoop();
}
}, 2000)
}
myLoop();
Thanks in advance!
You do not need nested loops. You can "linearize" them in single loop (I do not recall the correct therm now). So basically you want loop of 3 * 40 = 120 and after each 40 you need to use increased delay of 10 * 60 * 1000 = 600000. You help yourself by using modulo function i%40. Because you start with 1, the each 40th iteration is when remainder of i divided with 40 is zero.
So basically change if (i < 41) to if (i < 121) and }, 2000) to }, i%40 === 0 ? 600000 : 2000)
I need to increment the value from 0 to 103551 in 5 seconds. Below is the logic I have used. But it's not incrementing to the required value within 5 secs
var counter = 0;
var el = document.getElementById('seconds-counter');
function incrementSeconds() {
counter += 1;
el.innerText = "Processing " + counter + " execution records";
if(counter == 103551) {
console.log(new Date());
}
}
console.log(new Date());
var time = 103551/5000;
var cancel = setInterval(incrementSeconds, time);
HTML
<div id='seconds-counter'> </div>
Your math is a little off. 103551/5000 = 20.7102ms
1000ms = 1s, 5s = 5000ms, 5000/20.7102 = 240 iterations.
The equation you want to solve is 5000/x = numIterations
So x = 5000/numIterations
Note: Most browsers have a minimum number you can set in setInterval(), so you may need to increment by more than 1 each loop to count to 103551 in 5 seconds. Since this is an oddly specific problem I'm going to gues that this might be an assignment so will omit a full solution from this answer. Good luck!
Question
Every 2 seconds interval, the two numbers (i.e. Number 1 and Number 2) will generate random numbers containing integer values from 5 to 6.
For every random numbers generated, the 2 seconds interval will be reduced by 0.1 seconds.
The random speed text will show the current seconds interval for every random numbers generated.
Once the interval reaches 0.8 seconds, a javascript alert box will show the message “The interval has reached 0.8 seconds”.
When the user dismisses the alert, the random speed text is reset to the initial values and restarts the speed of two numbers to be randomly generated for every interval.
Current Code
var no1, no2, correctScore, wrongScore, missedScore, generatedNum, delay
generateTotal = 30;
function updateScreen(disabled) {
$('#correctScore').text(correctScore);
$('#wrongScore').text(wrongScore);
$('#missedScore').text(missedScore);
$('#generatedNum > span').text(generatedNum);
$("#number1 > span").text(no1);
$("#number2 > span").text(no2);
$(":input").val(generatedNum >= generateTotal ? "START!" : "MATCH!");
$(":input").prop('disabled', disabled);
}
function generate() {
if (no1 == no2 && !$(":input").prop('disabled')) ++missedScore;
if (generatedNum >= generateTotal) {
updateScreen(false); // needed to show missedScore.
if (confirm('The interval has reached 0.8 seconds')) start();
return; // exit
}
no1 = 5 + Math.floor(Math.random()*2);
no2 = 5 + Math.floor(Math.random()*2);
++generatedNum;
updateScreen(false);
setTimeout(generate, delay *= 0.95);
}
function start() {
correctScore = wrongScore = missedScore = generatedNum = 0;
delay = 2000;
updateScreen(true);
generate();
}
function check() {
if (generatedNum >= generateTotal) return start(); // Start pressed
if (no1 == no2) {
++correctScore;
} else {
++wrongScore;
}
updateScreen(true); // disable button
}
$(function(){
$(":input").click(check);
start();
});
$(function(){
$(":input").click(check);
start();
});
I need help with something I'm working on in JavaScript/jQuery
I'd like to give a set 'destination' number, and give it a set duration, and have it so it adds up in intervals of 1 randomly throughout the duration (not equally spaced, but not all at the start, end or middle), but reaching the 'destination' number by the duration of time is up.
So, if I set a duration of 20 seconds, and a 'destination' number of 10. It will start the timer, and randomly add in intervals of 1 (following no pattern), and the duration finishes at the same time as the last number is added.
I'm really stuck with this, and not sure where to even begin.
Any help at all would be greatly appreciated, thanks a lot!
My approach is:
Divide the duration to equal pieces (one for each increment, starting with 0, ending with the full duration)
Randomize the delays, but keep the same sum. If you add some random value to one delays, then subtract the same amount from delays interval.
Call window.setTimeout with all the delays. Give it a function witch increments the current value by one.
The code:
var start = parseInt($("#inStart").val(), 10),
end = parseInt($("#inEnd").val(), 10),
duration = parseInt($("#inDuration").val(), 10),
difference = end - start,
current = start - 1,
step = duration * 1000 / difference,
delays = [],
index, amount,
increment = function () {
current += 1;
$("#outCurrent").text(current);
};
// calculate equal delays
for (index = 0; index <= difference; index++) {
delays.push(step * index);
}
// randomize delays, without changing the sum
for (index = 1; index < delays.length - 2; index++) {
amount = (Math.random() - 0.5) * step;
delays[index] -= amount;
delays[index+1] += amount;
}
// schedule the increment calls
for (index = 0; index < delays.length; index++) {
window.setTimeout(increment, delays[index]);
}
Here is a demo fiddle, you can try it out.
Please Help! I'm new to Javascript, so there's probably an easier solution to this. Basically, I need it to prompt for a number and then count down from that number to zero. Once it reaches zero, I need it to count-up and stop at the same prompted number.
I got it to count down at first, then I completely butchered it, I have no clue what to do.
<script type="text/javascript">
// get number from user
var startNum = parseInt(prompt("Input a number to start counting down from.",""));
var counter = setInterval(timer, 1000);
console.log(startNum);
function timer() {
startNum--; // reduce number by 1
console.log(startNum);
if (startNum <= 0) {
clearInterval(counter);
}
}
var counter = setInterval(timer2, 1000);
var endNum = 0
function timer2() {
console.log(endNum)
endNum++; // add number by 1
console.log(endNum);
if (endNum >= startNum) {
clearInterval(counter);
}
}
</script>
You've got a couple issues here. the first one was pointed out by Rob in the comments. You're running both functions at the same time.
The other issue you have is that you're never storing the number. You're just subtracting and adding to nothing essentially.
So -
<script type="text/javascript">
// get number from user
var startNum = parseInt(prompt("Input a number to start counting down from.",""));
var currentNum = startNum;
var counter = setInterval(timer, 1000);
function timer() {
console.log(currentNum);
currentNum -= 1; // reduce number by 1
console.log(currentNum);
if (currentNum == 0) {
clearInterval(counter);
counter = setInterval(timer2, 1000);
}
}
function timer2() {
console.log(currentNum)
currentNum += 1; // add number by 1
console.log(currentNum);
if (currentNum == startNum) {
clearInterval(counter);
}
}
</script>
Something like this should do the trick. Basically creating another variable to hold your start number and consider that the current number and the value that is going to change.
here's a fiddle - http://jsfiddle.net/w5FM6/
cheers