¿How can I stop my number sequence from growing? [duplicate] - javascript

This question already has answers here:
JS - How to clear interval after using setInterval() [duplicate]
(4 answers)
Closed 6 years ago.
I am trying to make a sequence of numbers that starts with number 10 and grows like 10...11...12...13 etc every two seconds. But lets say that I want it to stop when it reaches 100, how do i do it. So far I have this.Any ideas?
function conteo(num){
setInterval(function(){document.write(num++ + "..."); }, 2000);
}conteo(10)

You can clear the interval:
function conteo(num){
var interval = setInterval(function() {
if(num == 100) {
clearInterval(interval);
}
document.write(num++ + "...");
}, 2000);
}
conteo(10)
This will check if num is equal to 100, then clear interval if true, but keep going.

Save the setInterval reference call into a variable:
var conteoInterval;
function conteo(num){
conteoInterval = setInterval(function(){document.write(num++ + "..."); }, 2000);
}
And to stop the interval, just clear its reference, doing this:
clearInterval(conteoInterval);

Related

Is it possible to have a variable interval within a javascript function?

I've been trying without success to set up a way of varying the interval used when incrementing a value by one. It's set to increment every 9 seconds but I'd like the counter to look a little less robotic and instead increment by a repeated variation of numbers, for example, 3 seconds, 7 seconds, 12 seconds, 10 seconds and 13 seconds (the five numbers add up to 45 to ensure an average of 9 seconds is maintained).
I've tried to put these numbers into an array and loop the value of 'interval' through them but I've now realised that value can't be changed within the context of the function once it's started.
Would be super grateful for any advice here. Thanks!
Current code for more 'robotic' count:
let interval = 9000;
let shiftCounter = {{ row.total }};
window.setInterval(function () {
document.getElementById("shiftsCreated").innerHTML = shiftCounter.toLocaleString('en');
shiftCounter = shiftCounter + 1;
}, interval);
You can use setTimeout instead, and every time it completes, call new timeout by choosing random delay or whatever order you want.
let counter = 0;
const intervals = [3, 7, 10, 12]
increment(0);
function increment(timeout) {
setTimeout(() => {
console.log(`Counter: ${counter}.`)
counter++;
increment(intervals[Math.floor(Math.random() * intervals.length)] * 1000)
}, timeout);
}

A button that can switch from increment to decrement at random, possible or not? [duplicate]

This question already has answers here:
javascript random pick variable
(2 answers)
JavaScript random generate 0 or 1 integer [duplicate]
(2 answers)
Closed 2 years ago.
quick question: Is it possible to set a button that can increment and or decrement a number as it is clicked? I want to know if such a feature is possible and if so, how?
You can use Math.random() to decide whether you are going to increment or not:
var counter = 0,
$counter = document.getElementById('counter'),
$myBtn = document.getElementById('myBtn');
$myBtn.addEventListener('click', incrementOrDecrement);
function incrementOrDecrement() {
var shouldIncrement = Math.random() > 0.5; // 50% chances of incrementing
counter += shouldIncrement ? 1 : -1;
$counter.innerText = counter;
}
<button id="myBtn">Change counter</button>
<h2 id="counter">0</h2>

How to make alert() come after .innerHTML? [duplicate]

This question already has answers here:
Javascript alert() supersedes preceding code
(4 answers)
Closed 2 years ago.
I currently have some code like this:
function markAlert() {
if (qnsAnsd == 4) {
alert("You got " + mark + "/4! Refresh page if you want to try again.")
};
}
function addEval() {
var addMrknElem = document.getElementById('q__add-mrkn');
qnsAnsdCntr();
document.getElementById('q__add-btn').disabled = true;
if (document.getElementById('q__add-ans').value == addSoln) {
addMrknElem.innerHTML = "Your answer is correct!";
markCntr();
} else {
addMrknElem.innerHTML = "Your answer is incorrect. The correct answer is " + addSoln + ".";
}
markAlert();
};
Basically title... I want the alert in markAlert() to pop up after the the .innerHTML takes effect.
just wrap your alert() method in the setTimeout See the example below.
setTimeout(() => {
markAlert()
}, 1000);
Here, 1000 means 1 second so this markAlert() will be invoked after 1 second. you can change this value to 500 means half a second too.

Increment by 1, then 10, then 100? [duplicate]

This question already has an answer here:
localStorage concatenating Integer instead of adding
(1 answer)
Closed 4 years ago.
So Im trying to write my program to where every time the function is activated, the value of 'money' in local storage goes up by 1. When I tested it out, It does go up by 1. But the next time, it went up by 10, then 100. Why? I couldnt find anyone with the same issue. Heres the code:
<script>
function changeText() {
localStorage.setItem("money", localStorage.getItem("money") + 1);
localStorage.setItem("map", true);
}
</script>
localStorage.getItem("money") will return a string, since it stores only string. When adding data to storage, it is implicitly converted to a string.
You can convert the string to number and then do addition and store the value
function changeText() {
if (localStorage.getItem('money') === null) {
localStorage.setItem('money', 1)
} else {
localStorage.setItem("money", +localStorage.getItem("money") + 1)
}
}
Try doing -
<script>
function changeText() {
var money = parseInt(localStorage.getItem("money"));
localStorage.setItem("money", money + 1);
localStorage.setItem("map", true);
}
</script>
parseInt converts string to number so if you pass parseInt("1") it will spit out 1 which will be of type number. Then you can add 1 to the number.
You are alomost there! Like others metioned here, localstorage works with strings and to convert a string to number just use the folowing in your code to return the value as number:
Number(your_string_number)
This should work for you:
<script>
function changeText() {
localStorage.setItem("money", Number(localStorage.getItem("money")) + 1);
localStorage.setItem("map", true);
}
</script>

What's the easiest way to call a function every 5 seconds in jQuery? [duplicate]

This question already has answers here:
Calling a function every 60 seconds
(15 answers)
Closed 5 years ago.
JQuery, how to call a function every 5 seconds.
I'm looking for a way to automate the changing of images in a slideshow.
I'd rather not install any other 3rd party plugins if possible.
You don't need jquery for this, in plain javascript, the following will work:
var intervalId = window.setInterval(function(){
// call your function here
}, 5000);
To stop the loop you can use:
clearInterval(intervalId)
you could register an interval on the page using setInterval, ie:
setInterval(function(){
//code goes here that will be run every 5 seconds.
}, 5000);
A good example where to subscribe a setInterval(), and use a clearInterval() to stop the forever loop:
function everyTime() {
console.log('each 1 second...');
}
var myInterval = setInterval(everyTime, 1000);
call this line to stop the loop:
clearInterval(myInterval);
Just a little tip for the first answer. If your function is already defined, reference the function but don't call it!!! So don't put any parentheses after the function name. Just like:
my_function(){};
setInterval(my_function,10000);
The functions mentioned above execute no matter if it has completed in previous invocation or not, this one runs after every x seconds once the execution is complete
// IIFE
(function runForever(){
// Do something here
setTimeout(runForever, 5000)
})()
// Regular function with arguments
function someFunction(file, directory){
// Do something here
setTimeout(someFunction, 5000, file, directory)
// YES, setTimeout passes any extra args to
// function being called
}
Both setInterval and setTimeout can work for you (as #Doug Neiner and #John Boker wrote both now point to setInterval).
See here for some more explanation about both to see which suits you most and how to stop each of them.
you can use window.setInterval and time must to be define in miliseconds, in below case the function will call after every single second (1000 miliseconds)
<script>
var time = 3670;
window.setInterval(function(){
// Time calculations for days, hours, minutes and seconds
var h = Math.floor(time / 3600);
var m = Math.floor(time % 3600 / 60);
var s = Math.floor(time % 3600 % 60);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = h + "h "
+ m + "m " + s + "s ";
// If the count down is finished, write some text
if (time < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
time--;
}, 1000);
</script>

Categories