So I'm trying to make a little "Matrix" themed program, I want the user to input their name, and then the program will run through 20 numbers every second as it displays each character of their name every 1 second, from left to right. What am I doing wrong? All that's working so far is the number scrolling
<html>
<head>
<script type="text/javascript">
var name = prompt("Enter Your Name to be 'MatrixIzed!':", "");
function numberScroll(){
for (i=0;i<name.length;i++){
setInterval(function() {
var n = Math.floor(Math.random() * 9);
document.getElementById('txt2').innerHTML = n;
}, 50);
setInterval(function() {
document.getElementById('txt1').innerHTML = name.charAt(i);
},1000);
}
}
</script>
</head>
<body onLoad="numberScroll()">
<div style="float:left" id="txt1"></div>
<div id="txt2"></div>
</body>
</html>
The setInterval is the loop, you don't need additional for loop. Also, you should set variable to store return value from set interval so you can clear it later when you want it to stop running.
function numberScroll(){
// no need to loop i, just set it and increment it in the interval
var i = 0;
// store interval as variable, so you can stop it later
var numbers = setInterval(function(){
var n = Math.floor(Math.random() * 9);
document.getElementById('txt2').innerHTML = n;
}, 50);
var letters = setInterval(function(){
// `+=` rather than `=` to incrementally add to the div's inner html
// use and increment i in one step with `i++`
document.getElementById('txt1').innerHTML += name.charAt(i++);
// when it has reached the end of the name, clear the intervals and empty the second div
if(i >= name.length){
clearInterval(numbers);
clearInterval(letters);
document.getElementById('txt2').innerHTML = '';
}
},500);
}
Fiddle (demo) here: http://jsfiddle.net/jW8hZ/
you need to iterate through all the letters inside the setInterval.
function numberScroll(){
setInterval(function() {
var n = Math.floor(Math.random() * 9);
document.getElementById('txt2').innerHTML = n;}
, 50);
var i=0;
setInterval(function() {
document.getElementById('txt1').innerHTML = name.charAt(i);
i = (i+1)%name.lenghth;
}
,1000);
}
Related
Im trying create some type of number generator on webpage. I want to show like five numbers before the generated number show. For better imagine, you can look to google generator. When you click generate, it shows like 3-4 numbers before generated number. I use setInterval or setTimeout but i dont know how it works. My js code:
var button = document.querySelector("button");
button.addEventListener("click",function() {
for (var i = 0; i < 8; i++) {
setInterval(textC,5);
}
});
function textC(){
number.textContent = Math.floor(Math.random() * 1000) + 1;
}
Thanks for every help!
The issue with setInterval() is that it will continue forever unless cleared, causing you to keep generating random numbers. Instead you can use setTimeout(), but set the timeout to change based on the value of i in the for loop. That way, each interval will occur 50 m/s after the other.
See example below:
const button = document.querySelector("button");
const number = document.querySelector("#number");
button.addEventListener("click", function() {
for (let i = 0; i < 5; i++) {
setTimeout(textC, 50 * i);
}
});
function textC() {
number.textContent = Math.floor(Math.random() * 1000) + 1;
}
<p id="number"></p>
<button>Generate</button>
Don't use a loop (why not?). Just nest setTimeout and call it until a predefined threshold is reached. It gives you maximum control.
var button = document.querySelector("button");
var number = document.querySelector("#number");
const nRuns = 12;
const timeout = 100;
let iterator = 0;
button.addEventListener( "click", textC);
function textC(){
number.textContent = `${Math.floor(Math.random() * 1000) + 1}\n`;
iterator += 1;
if (iterator < nRuns) {
setTimeout(textC, timeout)
} else{
iterator = 0;
// you control the loop, so it's time for some extra text after it
number.textContent += ` ... and that concludes this series of random numbers`;
}
}
<p id="number"></p>
<button>Generate</button>
I have been trying to find a answer for this but I couldn't really get it to work.
I need JavaScript code to display a random number 25 times with a 320ms delay for each number.
(Ignore the other things except for //start roll)
function roll() {
var win = Math.floor(Math.random() * 25) + 0
//change the button when rolling
rollButton.disabled = true;
rollButton.innerHTML = "Rolling...";
rollButton.style.backgroundColor = "grey";
rollButton.style.color = "black"
setTimeout(unDisable, 8000)
//start roll
(insert code here)
}
Thanks if you can help
You can use setInterval for make loop with some delay and clearInterval for stopping that loop !
$(function(){
t = 0;
var interval = setInterval(function(){
var win = Math.floor(Math.random() * 25) ;
var html = $('span').html();
$('span').html(html + win + '<br>')
t++;
if(t == 25)
stop();
}, 320);
function stop(){
clearInterval(interval);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span></span>
A simple thing you can do is simply:
function roll() {
//change the button when rolling
rollButton.disabled = true;
rollButton.innerHTML = "Rolling...";
rollButton.style.backgroundColor = "grey";
rollButton.style.color = "black"
setTimeout(unDisable, 8000)
//start roll
showNum(25)
}
const getRand = _ => Math.floor(Math.random() * 25) + 0
const showNum = n => {
if (n-- <= 0) {return}
document.getElementById("dispNum").innerHTML = getRand()
setTimeout(_ => showNum(n), 320)
}
It will keep spawning a new thread to print a random number while decrementing its iteration count, till it hits 0
I am using setInterval to run a Javascript function that generates a new, random integer in a div. the timer starts when I click on the div. I am having problems with stopping it form generating new numbers after five seconds.
Using setTimeout, I hide the div after 5 seconds; that stops random numbers, but I lose the div.
How can I efficiently stop the generating of numbers in the div, and not hide it?
HTML:
<div id="div" onmousedown='F();'>Click here</div>
JS:
function F(){
var div = document.getElementById("div");
setInterval(function(){
var number = Math.floor(Math.random()*28) ;
div.innerHTML = number;
}, 1000);
setTimeout(function(){
div.style.display = 'none';
},5000);
};
Just use a counter to keep track of the number of times the interval has ticked and then use clearInterval to stop it:
var count = 0;
var intervalID = setInterval(function() {
// generate your random number
count++;
if (count === 5) {
clearInterval(intervalID);
}
}, 1000);
Something hastily written, but what you want to do is keep track of your interval handle and then clear it. You can do this with a setTimeout
var forXsecs = function(period, func) {
var handle = setInterval(func, 1000);
setTimeout(function() { clearInterval(handle); }, period * 1000);
}
The timing is not perfect. Matt's answer would also work.
Another option is a slight change on Matt's answer that removes setInterval and just uses timeouts.
var count = 0;
var forXsecs = function(period, func) {
if(count < period) {
func();
count++;
setTimeout(function() {forXsecs(period, func);}, 1000);
} else {
count = 0; //need to reset the count for possible future calls
}
}
If you just want to simply let it run once each second and that 5 times you can do it like this:
HTML:
<div id="5seconds"></div>
JS:
var count= 0;
setInterval(function(){
if(count < 5){
document.getElementById('5seconds').innerHTML = Math.random();
count++
}
},1000);
This will generate a random number each second. until 5 seconds have passed
you should use clearInterval to stop the timer.
To do so, you pass in the id(or handle) of a timer returned from the setInterval function (which creates it).
I recommend clearing the interval timer (using clearInterval) from within the function being executed.
var elm = document.querySelector("div.container");
var cnt = 0;
var timerID;
function generateNumber()
{
cnt += 1;
elm.innerText = cnt;
if (cnt >= 5) {
window.clearInterval(timerID);
}
}
timerID = window.setInterval(generateNumber, 1000);
.container {display:block; min-width:5em;line-height:5em;min-height:5em;background-color:whitesmoke;border:0.1em outset whitesmoke;}
<label>1s Interval over 5s</label>
<div class="container"></div>
I am trying to run a loop that will continuously change the color by randomly generating hex codes. I tried to search on here but couldn't find anything doing this.
I can't figure out how to get a loop to run and change the color continuously (until the end of a loop). I am new to JavaScript.
Here's my JSFiddle.
HTML
<body>
<div id="outer">
<div id="test">Generate colors.</div>
</div>
</body>
JS
for ( i = 0; i < 20000; i++ ) {
var t = document.getElementById('test');
var z = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
t.style.color = z
}
You can't change colors in a loop, the color of the element won't change until you exit the code and return control to the browser.
You can use an interval to run code and return the control to the browser each time:
window.setInterval(function(){
var t = document.getElementById('test');
var z = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
t.style.color = z
}, 100);
Demo: http://jsfiddle.net/et3qtr3t/
You were right with the commented setInterval you have on fiddle. It will make the colors change periodically (according to the milliseconds defined).
But you have to remove the for loop, because it will run instantly and you won't even see the changes... You'll have to manage your own variable counter, and clear the interval after it:
http://jsfiddle.net/kkfnjpsh/5/
var i = 0;
var runner = setInterval(function(){
if(i < 20000) {
var t = document.getElementById('test');
var z = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
t.style.color = z;
i++;
}
else {
clearInterval(runner);
}
}, 3000);
I know it's already been answered, but mine includes the cleartimeout to set a timer.
var myVar = setInterval(function(){changeColor()}, 1000);
setTimeout(function(){clearInterval(myVar)}, 5000);
The second argument in the call to setTimeout could serve as your timer, so that the animation stops afterwards, in this case, it's set to 5 seconds.
function changeColor() {
var t = document.getElementById('test');
var z = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
t.style.color = z;
console.log(z);
}
Result: Result
You don't loop - you interval:
var target= document.getElementById('test'),
colorChange = function() {
target.style.color = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
};
// run interval
var d = setInterval(function() {
colorChange();
}, 500);
// clear after 5s
setTimeout(function() {
clearInterval(d);
}, 5000);
Working JSFiddle: http://jsfiddle.net/046q6ohf/
So I've got this counter and it needs to increment a number by 75 every 60 seconds. The code I have below does this fine but due to rounding some numbers stay up longer than others, and some numbers are skipped.
I'd rather have this to smoothly/evenly count to get the same end result. I know I would need to somehow calculate the setInterval timer number, but I'm not sure what to get that.
(function(){
//Numbers
var num = 0;
var perMinute = 75;
var perSecond = perMinute / 60;
//Element selection
var count = document.getElementById("count");
function update(){
//Add the per-second value to the total
num += perSecond;
//Display the count rounded without a decimal
count.innerHTML = Math.round(num);
}
//Run the update function once every second
setInterval(update, 1000);
})();
Working example: http://jsfiddle.net/ChrisMBarr/9atym/1/
Never rely on Timeout or Interval to be accurate. Instead, save the "start time" and compare it to the current time.
(function() {
var start = new Date().getTime(),
perMinute = 75,
perMS = perMinute/60000,
count = document.getElementById('count');
function update() {
var elapsed = new Date().getTime()-start;
count.innerHTML = Math.round(elapsed*perMS);
}
setInterval(update,1000);
})();
Note that you can adjust the 1000 to vary "smooth" the counter is (more important for bigger values of perMinute) and it will always work perfectly, to within the resolution's overshoot.
Moving your rounding seemed to fix this (Edit: No it doesn't. See the jsfiddle example of a better fix I put below).
(function(){
//Numbers
var num = 0;
var perMinute = 75;
var perSecond = perMinute / 60;
//Element selection
var count = document.getElementById("count");
function update(){
//Add the per-second value to the total
num += Math.round(perSecond);
//Display the count rounded without a decimal
count.innerHTML = num;
}
//Run the update function once every second
setInterval(update, 1000/perSecond);
})();
Edit: a proper fix - http://jsfiddle.net/4y2y9/1/