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
Related
I want to display an animated number from 0 to max value y during x seconds. I have tried this following code but it take too much to complete and clear the interval.
jQuery('.numbers').each(function(item, index) {
const $obj = jQuery(this);
let objValue = parseInt($obj.text()),
currentValue = 0,
speed = 1,
time = 4000,
step = Math.floor(objValue / time);
$obj.text(currentValue);
let interVal = setInterval(() => {
if (currentValue >= objValue) {
clearInterval(interVal);
$obj.text(objValue);
}
$obj.text(currentValue);
currentValue += step
}, speed);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class='numbers'>7586</span>
<span class='numbers'>147520</span>
How do I play this animation during exactly time seconds?
It is better not to depend on the timing of setInterval(), but the real problem in your script is that you use the floored value to decide the new value to print out.
It is better to use Window.requestAnimationFrame() and create a update() function that prints the current number based on the real time elapsed.
let start, previousTimeStamp;
let numbers = document.querySelectorAll('.numbers');
requestAnimationFrame(update);
function update(timestamp) {
if (start === undefined) {
start = timestamp;
}
const elapsed = timestamp - start;
[...numbers].forEach(elm => {
if(!elm.dataset.start){
elm.dataset.start = elm.textContent;
}
let start = parseInt(elm.dataset.start);
elm.textContent = Math.floor(start / 4000 * elapsed);
});
if (elapsed < 4000) {
previousTimeStamp = timestamp;
requestAnimationFrame(update);
}else {
start = undefined;
[...numbers].forEach(elm => {
elm.textContent = elm.dataset.start;
});
}
}
<span class='numbers'>7586</span>
<span class='numbers'>147520</span>
The goal is to make the button turn off if pressed 10 times in less than 1 minute but keep counting if not pressed 10 times in 1 minute? so only disables when pressed 10 times in less than 1 minute. You can click nine times in a minute but nothing happens but the tenth time the button turns off, but if the minute has passed you can keep clicking but always for a maximum ten times and the counter does not reset but continues to increase in number.
let accCounter = 0;
let totalCount = 0;
document.getElementById('totalCounter').innerText = totalCount;
document.getElementById('clap').onclick = function() {
const clap = document.getElementById('clap');
const clickCounter = document.getElementById("clicker");
upClickCounter();
function upClickCounter() {
const clickCounter = document.getElementById("clicker");
const totalClickCounter = document.getElementById('totalCounter');
accCounter++;
clickCounter.children[0].innerText = '+' + accCounter;
totalClickCounter.innerText = totalCount + accCounter;
}
}
var endCount = 5; // 5 for testing - this would be 10
var interval = 5000 // 5s for testing, 1 min= 1000 * 60;
var clicks = [];
var totalClicks = 0;
$("#btn").click(function() {
clicks.push(Date.now());
totalClicks++;
checkIt();
})
function checkIt() {
//if (clicks.length < endCount) return;
while (clicks.length && (Date.now() - clicks[0]) > interval) {
console.log("removing: " + ((Date.now() - clicks[0]) / 1000))
clicks.shift();
}
if (clicks.length < endCount) return;
$("#btn")[0].disabled = true;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="clap" class="clap-container"></button>
<div id="totalCounter" class="total-counter"></div>
<div id="clicker" class="click-counter"></div>
Im wondering what is wrong with this for loop here. I'm trying to make a Pomodoro Study Timer, a study technique that suggests that you break down studying into 25-minute chunks that are followed by 3-5 minute breaks. here I have 2 timers that run in sequence, one after the other. When the first timer reaches zero, the second one starts. For now, i have timers set to 5 seconds and 3 seconds respectively in order to make testing quicker. It all works fine until I put the whole thing into a for loop which then brings some unexpected behaviour. I want to loop the entire function based on user input which informs the code on how many times to loop the counters(this isnt setup yet).
The timers are started by pressing a button on an html page. The button executes the pomo() function at the bottom, which contains a loop that should loop the start() function.
PS, I'm a total ultra noob so apologies if this is just terrible code, I'm really new to this :)
var time25 = 5;
var time5 = 3;
var timeElapsed25 = 0;
var timeElapsed5 = 0; // initializes time elapsed to zero
var time = document.getElementsByClassName("header"); //links to html
time[0].innerHTML = time25; // sets output to html
function convertToMin(s) {
mins = Math.floor(s / 60);
let minsStr = mins.toString();
if (minsStr.length === 1) {
mins = '0' + mins;
}
sec = s % 60;
let secStr = sec.toString();
if (secStr.length === 1) {
sec = '0' + sec;
}
return mins + ':' + sec;
}
function start() {
var timer25 = setInterval(counter25, 1000);
console.log("timer1");
function counter25() {
timeElapsed25++
time[0].innerHTML = convertToMin(time25 - timeElapsed25);
if (timeElapsed25 === time25) {
console.log("timer2")
clearInterval(timer25);
timeElapsed25 = 0;
var timer5 = setInterval(counter5, 1000);
function counter5() { //Counter For 5 minute break
timeElapsed5++;
time[0].innerHTML = convertToMin(time5 - timeElapsed5);
if (timeElapsed5 === time5) {
clearInterval(timer5);
timeElapsed5 = 0;
}
}
}
}
}
function pomo() {
for (j = 0; j < 3; j++) {
start();
}
}
You shouldn't call start() in a loop. setInterval() doesn't wait for the the countdown to complete, it returns immediately, so you're starting all 3 timers at the same time.
What you should do is call start() again when both timers complete. To put a limit on the number of repetitions, use a count parameter, and decrement it each time you call again.
var time25 = 5;
var time5 = 3;
var timeElapsed25 = 0;
var timeElapsed5 = 0; // initializes time elapsed to zero
var time = document.getElementsByClassName("header"); //links to html
time[0].innerHTML = time25; // sets output to html
function pomo() {
start(3);
}
function start(count) {
if (count == 0) { // reached the limit
return;
}
var timer25 = setInterval(counter25, 1000);
console.log("timer1");
function counter25() {
timeElapsed25++
time[0].innerHTML = convertToMin(time25 - timeElapsed25);
if (timeElapsed25 === time25) {
console.log("timer2")
clearInterval(timer25);
timeElapsed25 = 0;
var timer5 = setInterval(counter5, 1000);
function counter5() { //Counter For 5 minute break
timeElapsed5++;
time[0].innerHTML = convertToMin(time5 - timeElapsed5);
if (timeElapsed5 === time5) {
clearInterval(timer5);
timeElapsed5 = 0;
start(count - 1); // Start the next full iteration
}
}
}
}
}
function convertToMin(s) {
mins = Math.floor(s / 60);
let minsStr = mins.toString();
if (minsStr.length === 1) {
mins = '0' + mins;
}
sec = s % 60;
let secStr = sec.toString();
if (secStr.length === 1) {
sec = '0' + sec;
}
return mins + ':' + sec;
}
I would like to add an effect that some websites now have i.e. coffees drank: and then number of coffees drank, gradually growing from 0 to N-1. This is my attempt, if I print i in the console in the first if statement , each number prints out. But, when in HTML it goes from 0-950 instantly with no numbers in between.
To sum make it up: I would like the number to increment on the page, each new number replacing its previous number.
for (i = 0; i < 950; i++) {
if ($("#counter").length) {
setTimeout(function() {
// body...
$("#counter").append('<p id = "counter">' + i + '</p>');
}, 2000);
console.log(i);
} else {
$(".coffee-drank").append('<p id = "counter">' + i + '</p>');
}
}
If I got your idea correctly, it can be done generally like this:
var start = -1, end = 950;
var countUp = function func() {
if(start >= end) return;
var elem = document.getElementById("counter");
elem.innerText = ++start;
setTimeout(func, 25);
}
countUp();
count up to 950:
<span id="counter">0</span>
UPDATE
In your case it might look like this (no need for a cycle at all):
var start = -1, end = 950;
var countUp = function func() {
if(start >= end) {
// the end is reached; start is equal to 950 now; do something useful and quit
$(".coffee-drank").append('<p id = "counter">' + start +'</p>');
return;
}
$("#counter").text(++start);
setTimeout(func, 25);
}
countUp();
Replace your for loop with this:
var speed = 16; // Lower is faster
increase(0, 950);
function increase(i, max){
if(i <= max){
if ($("#counter").length) {
$("#counter").html(i);
} else {
$(".coffee-drank").append('<p id = "counter">' + i + '</p>');
}
setTimeout(function(){
increase(++i, max);
}, speed);
}
}
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);
}