Rolling numbers in js - javascript

I created rolling numbers
On the site I'm building in React.
How do I make it start working that it gets to the working place that it is?
It's starting to work for me that the page comes up
const RollingNumbers = () => {
useEffect(() => {
let valueDisplays = document.querySelectorAll(".amount");
let interval = 4000;
valueDisplays.forEach((valueDisplay) => {
let startValue = 0;
let endValue = parseInt(valueDisplay.getAttribute("data-val"));
let duration = Math.floor(interval / endValue);
let counter = setInterval(function () {
startValue += 1;
valueDisplay.textContent = startValue;
if (startValue === endValue) {
clearInterval(counter);
}
}, duration);
});
enter image description here
Thank you

Related

react decibel meter and use

i need to make a decibel meter
i try to use 2 libary but they wont work and they very old
i found a function that make this but it wont work as expected
first of all the issue is
inside this function i get the
" let decibelNumString = decibelNum.toString().substring(0, 2); "
which is get me the number of the decibel and make it to integear
but
i want to make the minNumber and MaxNumber as state because it should re render after the changes happen
the probme it make a lot of re render becuase every 100ms it change the numbers
i have also the current decibel so it need to be render every 100ms
and it not good for perfomance
// const [minNumber, setMinNumber] = useState(25);
// const [maxNumber, setMaxNumber] = useState(30);
let arr = [];
let volumeCallback = null;
let volumeInterval = null;
(async () => {
// Initialize
try {
const audioStream = await navigator.mediaDevices.getUserMedia({
audio: {
echoCancellation: true,
},
});
const audioContext = new AudioContext();
const audioSource = audioContext.createMediaStreamSource(audioStream);
const analyser = audioContext.createAnalyser();
analyser.fftSize = 512;
analyser.minDecibels = -127;
analyser.maxDecibels = 0;
analyser.smoothingTimeConstant = 0.4;
audioSource.connect(analyser);
const volumes = new Uint8Array(analyser.frequencyBinCount);
volumeCallback = () => {
analyser.getByteFrequencyData(volumes);
let volumeSum = 0;
for (const volume of volumes) volumeSum += volume;
const averageVolume = volumeSum / volumes.length;
// Value range: 127 = analyser.maxDecibels - analyser.minDecibels;
let decibelNum = (averageVolume * 100) / 127;
let decibelNumString = decibelNum.toString().substring(0, 2);
if (Number(decibelNumString) > maxNumber) {
// (maxNumber = Number(decibelNum))
// setMaxNumber((prev) => {
// return (prev = Number(decibelNumString));
// });
}
if (Number(decibelNumString) < minNumber) {
// setMinNumber((prev) => {
// return (prev = Number(decibelNumString));
// });
}
console.log(decibelNumString);
// console.log(minNumber + "min");
// console.log(maxNumber + "max");
arr.push(Number(decibelNumString));
// console.log(arr)
};
} catch (e) {
console.error("Failed to initialize volume visualizer, simulating instead...", e);
// Simulation
//TODO remove in production!
let lastVolume = 50;
volumeCallback = () => {
const volume = Math.min(Math.max(Math.random() * 100, 0.8 * lastVolume), 1.2 * lastVolume);
lastVolume = volume;
};
}
// Use
// start();
})();
const stop = () => {
clearInterval(volumeInterval);
// volumeInterval = null;
};
const start = () => {
// Updating every 100ms (should be same as CSS transition speed)
if (volumeCallback !== null && volumeInterval === null) volumeInterval = setInterval(volumeCallback, 100);
};

Metronome JavaScript - function .pause() don't stop the Audio beep

I trying to do a metronome on Codepen.
But I have one problem because the function .pause() doesn't stop the beep(my sound).
This is the code that I wrote. I read about it but I don't find the problem.
The audio I found on Codepen. I don't think it's the problem. I think the problem is between my computer and my chair.
const beep = new Audio(
"data:audio/flac;base64,ZkxhQwAAACIQABAAAARBAARBAfQBcAAAAZLfwZb9QVlTtnnZLOsaWczxhAAAKCAAAAByZWZlcmVuY2UgbGliRkxBQyAxLjMuMCAyMDEzMDUyNgAAAAD/+HQMAAGRJhgKxHRX63x+6QxXqTpCYAANDJgITNAmIhAB/5BgFt4iAfgBZHY4A9UZAAZ65QManTnQUAKnx8A+ZcwFun6gX1gMVIgAfaXgEml9KIzgfUBYAnhLwJl/Oek+A5rZADhx2ApN3s198CTrfAPyHMGRV3DcKAYAAwBJ7uA8wysUF8HYV6AUyIIKv/ObD0B7BRAOf6QFVnlVIrg0zuwGYTqCTP9rJXAWm4AC1HQDxVMnllwVg94CGPDDq6XrJRgQ2zwHp6wGR5tQFGh9dygZtwIXeHNK+AHAw8BZ34BSgBUY44Ze3IEt2uEhBfQg3BcaTA+MSB/rIUTNIUTWYN9hMdT2M/TYEg+cDC6KGzFJQAzj8TBBUujjHFLnsqB07TAj7JBa4qT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display');
const time = document.getElementById('time');
const timeSlice = document.getElementById('time-slice');
const rangeBpm = document.getElementById('bpm-range');
const btnStartStop = document.getElementById('start-stop');
const btnReset = document.getElementById('reset');
let intervalSound
// function to start and stop the metronome
const startMetronome = (() => {
btnStartStop.innerText==='Start'? btnStartStop.innerText= 'Stop': btnStartStop.innerText='Start';
if(btnStartStop.innerText === 'Stop'){
intervalSound = (60/bpm.value) * 1000;
console.log(intervalSound);
interval(intervalSound);
}
else{
stopBeat();
}
});
const stopBeat = (()=>{
beep.pause();
beep.currentTime = 0;
})
const playBeat = (() =>{
beep.play();
})
const interval = ((interval) => {
setInterval(playBeat, interval)
})
// function to reset all metronome
const resetMetronome = (()=>{
bpm.value = '120';
rangeBpm.value='120';
time.value='4';
timeSlice.value='4';
intervalSound = 0;
stopBeat();
});
btnReset.addEventListener('click', function(){resetMetronome()});
btnStartStop.addEventListener('click', function(){startMetronome()});
bpm.addEventListener('change', function(){
rangeBpm.value=bpm.value;
})
rangeBpm.addEventListener('click', function(){
bpm.value = rangeBpm.value;
})
console.log(bpm.value, time.value, timeSlice.value, rangeBpm.value, btnStartStop.innerText, btnReset.innerText);
Can you help me?
You need to clear your interval.
let intervalId = -1;
const stopBeat = (()=>{
beep.pause();
beep.currentTime = 0;
clearInterval(intervalId);
})
const interval = ((interval) => {
intervalId = setInterval(playBeat, interval)
})

How to update setInterval data every x seconds without affecting inside setInterval?

How can i update ranType every 30 seconds.
since ranType is random if ranType === 'works' how to add interval to update inside data every 10 seconds.
This is what i tried:
setInterval(() => {
let type = ['works', 'testing'];
let ranType = type[Math.floor(Math.random() * type.length)];
if (ranType === 'works') {
setInterval(async () => {
console.log(`Okay Working ${RANDOM DATA}`);
}, 10000);
} else {
setInterval(async () => {
console.log(`Testing also working ${RANDOM DATA}`);
}, 10000); // But RANDOM DATA should update every 10 seconds - I have RANDON data
}
}, 30000); // ranType should update every 30 seconds
expected output:
After 30 seconds
if ranType is 'works'
it should repeat console with random data every 10 seconds
Again after 30 seconds it (ranType) should change to testing
if ranType is 'testing'
it should repeat console with other random data every 10 seconds
Other issues is its keep repeting 3-4 times every 10 seconds.
Ok, I think this is what you want, please let me know if is not the expected result. Every 30 seconds the outer setInterval clears the last intervalId and creates a new one.
let intervalId;
setInterval(() => {
let type = ["works", "testing"];
let ranType = type[Math.floor(Math.random() * type.length)];
console.log("new cycle of interval of 30 seconds");
clearInterval(intervalId);
setTimeout(() => {
if (ranType === "works") {
intervalId = setInterval(async () => {
console.log(`Okay Working`);
}, 10000);
} else {
intervalId = setInterval(async () => {
console.log(`Testing also working`);
}, 10000);
}
});
}, 30000);
EDIT
created a new version which might be clearer
const setIntervalXTimes = (callback, delay, repetitions) => {
let count = 0;
let intervalID = setInterval(() => {
if (count === repetitions) {
clearInterval(intervalID);
} else {
callback();
}
count++;
}, delay);
};
setInterval(() => {
let type = ["works", "testing"];
let ranType = type[Math.floor(Math.random() * type.length)];
if (ranType === "works") {
setIntervalXTimes(() => console.log(`Okay Working`), 1000, 3);
} else {
setIntervalXTimes(() => console.log(`Testing also working`), 1000, 3);
}
}, 3000);
const ranType_reset_period = 30000;
const works_reset_period = 10000;
const testing_reset_period = 10000;
const random_data_reset_period = 10000;
let works_interval = -1;
let testing_interval = -1;
let RANDOM_DATA = "RANDOM_DATA_DEFAULT";
function reset_random_data() {
let sample_random_data = ['RANDOM_DATA_1', 'RANDOM_DATA_2', 'RANDOM_DATA_3', 'RANDOM_DATA_4'];
RANDOM_DATA = sample_random_data[Math.floor(Math.random() * sample_random_data.length)];
console.log('RANDOM_DATA', 'RESET', RANDOM_DATA);
}
function get_random_ranType() {
let type = ['works', 'testing'];
return type[Math.floor(Math.random() * type.length)];
}
function reset_works_interval() {
console.log(`Okay Working ${RANDOM_DATA}`);
}
function reset_testing_interval() {
console.log(`Testing also working ${RANDOM_DATA}`);
}
function reset_rantype() {
clearInterval(works_interval);
clearInterval(testing_interval);
if (get_random_ranType() === 'works') {
works_interval = setInterval(reset_works_interval, works_reset_period);
} else {
testing_interval = setInterval(reset_testing_interval, testing_reset_period); // But RANDOM DATA should update every 10 seconds - I have RANDON data
}
}
setInterval(reset_random_data, random_data_reset_period);
setInterval(reset_rantype, ranType_reset_period);
Illustration
const ranType_reset_period = 30000;
const works_reset_period = 10000;
const testing_reset_period = 10000;
const random_data_reset_period = 10000;
let works_interval = -1;
let testing_interval = -1;
let RANDOM_DATA = "RANDOM_DATA_DEFAULT";
function reset_random_data() {
let sample_random_data = ['RANDOM_DATA_1', 'RANDOM_DATA_2', 'RANDOM_DATA_3', 'RANDOM_DATA_4'];
RANDOM_DATA = sample_random_data[Math.floor(Math.random() * sample_random_data.length)];
console.log('RANDOM_DATA', 'RESET', RANDOM_DATA);
}
function get_random_ranType() {
let type = ['works', 'testing'];
return type[Math.floor(Math.random() * type.length)];
}
function reset_works_interval() {
console.log(`Okay Working ${RANDOM_DATA}`);
}
function reset_testing_interval() {
console.log(`Testing also working ${RANDOM_DATA}`);
}
function reset_rantype() {
clearInterval(works_interval);
clearInterval(testing_interval);
if (get_random_ranType() === 'works') {
works_interval = setInterval(reset_works_interval, works_reset_period);
} else {
testing_interval = setInterval(reset_testing_interval, testing_reset_period);
}
}
setInterval(reset_random_data, random_data_reset_period); // But RANDOM DATA should update every 10 seconds - I have RANDON data
setInterval(reset_rantype, ranType_reset_period);

Moment JS subtract problems

I'm setting up a timer with moment, is not the only one I have in this screen but this doesn't work:
const halfBellTimer = () => {
const x = setInterval(() => {
let countTime = moment.duration().add({seconds: meditationTime / 2});
if (countTime <= 0) {
console.log('STOP');
} else {
countTime = countTime.subtract(1, 's');
console.log(countTime.seconds());
}
}, 1000);
};
It sets the time correctly but I get a log of the same value, so it doesn't subtract it.
Any idea?
Thanks!
If you move let countTime = moment.duration().add({seconds: meditationTime / 2});
outside of setInterval function it works fine.
Don't forget to clean up with clearInterval.
Take a look at the example.
const halfBellTimer = () => {
const meditationTime = 10;
let countTime = moment.duration().add({
seconds: meditationTime / 2
});
const x = setInterval(() => {
if (countTime <= 0) {
console.log('STOP');
clearInterval(x);
} else {
countTime = countTime.subtract(1, 's');
console.log(countTime.seconds());
}
}, 1000);
};
halfBellTimer();
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.min.js"></script>

Totally destroy an instance

I am making a game with rounds that last either 100 minutes OR the time required for totalItemAmount to reach 500.
If "addPlayer" gets triggered when the game has ended, I want to push that player to next round.
I want to be able to destroy it/create new ones flawlessly.
First game always runs well.
Following games go wrong. To sum it up, I feel like the first game ran isn't being properly destroyed after it ends. Obviously, my code is much much larger than what you see down here, but let me ask you, is there any problem with my structure?
function Game(duration, playersForThisRound) {
console.log('NEW GAME')
this.playersForNextRound = [];
this.id = Math.random();
this.finished = 0;
this.players = {};
this.duration = 100;
this.totalItemAmount = 0;
this.endTimeout = setTimeout(() => {
this.end(this);
return
}, this.duration * 60 * 1000);
if (playersForThisRound && playersForThisRound.length > 0) {
Object.keys(this.playersForNextRound).forEach(function(key) {
this.addPlayer(this, key.player, key.items)
});
}
return
}
Game.prototype.addPlayer = function(game, player) {
if (this.finished || this.totalItemAmount >= 500) {
var playerIsInNextRound = 0;
Object.keys(this.playersForNextRound).forEach(function(key) {
if (key.id == player.id) {
playerIsInNextRound = 1
key.items.push(items)
}
})
if (!playerIsInNextRound)
this.playersForNextRound.push({
"id": player.id,
"player": player,
"items": items
});
if (game.totalItemAmount >= 500) {
clearTimeout(game.endTimeout)
this.end(this);
}
return
}
if (!game.players[player.id]) {
game.players[player.id] = new Player(game, player, items);
game.players[player.id].addItems(game, items, function(added) {
game.jackpot += added;
Object.keys(game.players).forEach(function(player) {
game.players[player].chance = game.players[player].getChance(game.jackpot)
});
})
}
Game.prototype.end = function(game) {
game.finished = 1;
clearTimeout(game.endTimeout)
setTimeout(() => {
game = new Game(10, this.playersForNextRound);
}, 1000 * 60 * 10);
}
//To start first game
var game = new Game();
module.exports = game;
Now in another file:
let game = require("./lib/games/roundbased.js");
let test = setInterval(() => {
for (var i = 0; i < 100; i++) {
game.addPlayer(game, {
id: '12345' + i,
nick: "player" + i
},

Categories

Resources