How to Increment a Number After Every 1 Second Using JavaScript

Increment integer by 1; every 1 second

You can use setInterval() for that reason.

var i = 1;

var interval = setInterval( increment, 1000);

function increment(){
i = i % 360 + 1;
}

edit: the code for your your followup-question:

var interval = setInterval( rotate, 1000);

function rotate(){
percentArrow.rotate(1,150,150);
}

I'm not entirely sure, how your rotate works, but you may have to store the degrees in a var and increment those var too like in the example above.

Javascript - display incrementing number every second

When you create a setInterval once, it will automatically call function (first argument) every 1000 milliseconds (second argument). So you don't need to do it inside while, just put incrementing of i inside the function (first argument).

function counter() {
var i = 0;
// This block will be executed 100 times.
setInterval(function() {
if (i == 100) clearInterval(this);
else console.log('Currently at ' + (i++));
}, 1000);
} // End

counter()

How can I increment a number after every 1 second using javascript?

Use setInterval to add delay.

See comments inline in the code:

$(document).ready(function() {
var number = parseInt($('#test').text(), 10) || 0; // Get the number from paragraph


// Called the function in each second
var interval = setInterval(function() {
$('#test').text(number++); // Update the value in paragraph

if (number > 1000) {
clearInterval(interval); // If exceeded 100, clear interval
}
}, 1000); // Run for each second
});

DEMO

Increasing count of number every second?

This should do what you're asking for:

setTimeout(start, 5000);
var i = 1;var num = document.getElementById('number');
function start() { setInterval(increase, 1000);}
function increase() { if (i < 100) { i++; num.innerText = i; }}
<div id="number">1</div>

using setInterval to increment variable every second - not updating

You should uses a functional state update, so instead of setSec(sec+1) write setSec(prevSec => prevSec + 1)

See the React Hooks API for reference: https://reactjs.org/docs/hooks-reference.html#usestate

Every 1 second increase the value with a random number using decimal numbers

Your problem is that you are setting number to 0 in each execution, while it should be the current value.

You need to assign Number(document.getElementById("computerScore").textContent) to it, so it keeps updating with the added random number.

Note that I used textContent which is recommended here as it holds only the text content of the element avoiding HTML elements.

setInterval (function myFunction() {
var number = Number(document.getElementById("computerScore").textContent);
document.getElementById("computerScore").textContent= number +
Math.floor((Math.random() * 5) + 1)/100;
}, 1000)

Demo:

setInterval (function myFunction() {  var number = Number(document.getElementById("computerScore").textContent);  document.getElementById("computerScore").textContent = number +   Math.floor((Math.random() * 5) + 1)/100;}, 1000)
<b>computer score:</b><p id="computerScore">0</p>

How to increment a state variable every second in React

Issue

The issue here is you've a stale enclosure of the currImageIndex state value from the initial render when the increment callback was setup in the interval timer. You're correctly using a functional state to increment the currImageIndex value, but the currImageIndex value in the increment function body is and always will be that of the initial state value, 0.

Solution

A common solution here would be to use a React ref to cache the currImageIndex state so the current value can be accessed in callbacks.

Example:

const [currImageIndex, setCurrImageIndex] = useState(0);
const currentImageIndexRef = useRef();

useEffect(() => {
// cache the current state value
currentImageIndexRef.current = currentImageIndex;
}, [currImageIndex]);

const increment = () => {
// access the current state value
if (currentImageIndexRef.current + 1 < url.length) {
setCurrImageIndex((oldCount) => oldCount + 1)
}
else {
setCurrImageIndex(0)
}
}

useEffect(() => {
const id = setInterval(increment, 1000);
return () => clearInterval(id);
}, []);

A simpler solution is to just access the url value that is closed over in component scope with the state updater callback. Use a ternary operator to check if adding 1 to the current value is still less than the url length and state + 1, otherwise reset by returning 0. Note however that if the url array is dynamic and the length changes this solution breaks for the same reason, the url value from the initial render is closed over in scope.

const increment = () => {
setCurrImageIndex((count) => count + 1 < url.length ? count + 1 : 0);
}

And IMO the simplest solution is to just increment the currImageIndex state always and take the modulus of the url length to always compute a valid, in-range index value. If the url array changes, it doesn't matter as the modulus function will always compute a valid index.

const { url } = props;
const [index, setIndex] = useState(0);
const increment = () => setIndex(i => i + 1);

useEffect(() => {
const id = setInterval(increment, 1000);
return () => clearInterval(id);
}, []);

const currImageIndex = index % url.length;

return (
<div className={styles.container}>
<div className={styles.header}>Preview of GIF:</div>
<img src={url[currImageIndex]} alt="GIF Preview" className={styles.image} />
<div>{currImageIndex}</div>
</div>
);

Edit how-to-increment-a-state-variable-every-second-in-react



Related Topics



Leave a reply



Submit