storing the value of setInterval - javascript

if I had a code like this
count=0
count2=setInterval('count++',1000)
the count2 variable would always set as 2 not the actual value of count as it increases every second
my question is: can you even store the value of the seInterval() method

The return value of setInterval() is an ID number that can be passed to clearInterval() to stop the periodically executed function from running another time. Here's an example of that:
var id = setInterval(function() {
// Periodically check to see if the element is there
if(document.getElementById('foo')) {
clearInterval(id);
weAreReady();
}
}, 100);
In your example, if you want count2 to have the same value as count, you could use:
var count = 0, count2 = 0;
setInterval(function() {
// I wrote this on two lines for clarity.
++count;
count2 = count;
}, 1000);

setInterval returns an ID which you can later use to clearInterval(), that is to stop the scheduled action from being performed. It will not be related to the count values in any way.

var count=0;
function incrementCount(){
count++;
}
setTimeout("incrementCount()", 1000);

Related

setInterval is not working with innerHTML?

I am trying to create a small place on my website to show the seconds running. but my javascript function is not running. At the same time, it does not show any error. This is my javascript code:
function stoptime() {
let count = 0;
count = count+1;
stop = document.getElementById("time");
stop.iinnerHTML = count.value;
setInterval(stoptime, 1000);
I can use this code with document.write function, but it did not give the count ++ value, instead of that it showed many single value of count. so I tried to use it with innerHtml, but it not running.
please tell, what is the reason and the correct code?
HTML
<span id="time"></span>
JS
let count = 0;
function stoptime() {
count++
stop = document.getElementById("time");
stop.innerHTML = count;
}
setInterval(stoptime, 1000);
The count variable is initialized in the same function every time. Its value gets reset to 1 each time the function is called. Moving the count declaration outside the function should fix your issue.
Also you don't need count.value
let count = 0;
function stoptime() {
count = count+1;
stop = document.getElementById("time");
stop.innerHTML = count;
}
setInterval(stoptime, 1000);
<div id="time"></div>

JavaScript variable changing between two values on a regular basis [duplicate]

This question already has answers here:
Is there a better way of writing v = (v == 0 ? 1 : 0); [closed]
(31 answers)
Closed 5 years ago.
I want a variable's value regularly changing between 0 and 1. If I have a variable whose value is 0 (counter = 0), how can I increase it by 1 (counter = 1) after a few seconds, then decrease it back to 0 ( counter = 0) after another few seconds? An endless loop basically is what I want.
I'm assuming this will require setTimeout or setInterval, but I've absolutely no idea how I'd go about this. I'm very unfamiliar with the syntax; I'm very much a newbie. Does anyone have any pointers?
Thanks!
You can create an endless, timed loop by having a function that calls itself at the end via setTimeout. See below.
var count = 0;
function flip() {
count = Number(!count);
console.log(count);
setTimeout(flip, 1000);
}
flip();
A more generic approach:
// possible addition: allow user to stop the timer
const rotate = (time, vals) => {
// TODO: handle incorrect vals (non-empty array) or time (positive number)
let idx = 0;
setInterval(() => idx = (idx + 1) % vals.length, time);
return {
get val() {return vals[idx];}
}
}
const toggle = rotate(1000, [0, 1])
toggle.val //=> depends on when you call it, changes every 1000 ms
// but always either 0 or 1.
One advantage of this is that it doesn't keep the value in global scope where someone else can mess with it, but encapsulates it in a closure.
It's more generic because you can easily change the time between updates and you can choose whatever you want for values (for example, rotate(5000, ['foo', 'bar', 'baz').)
var counter = 0;
var changeCounter = function () {
counter = counter === 0 ? 1 : 0;
console.log('counter', counter);
setTimeout(changeCounter, 1000);
}
changeCounter();
This sounds like homework but try this:
var value = 0;
setInterval(
function() {
value = value===0 ? 1 : 0;
console.log('value =', value);
},
1000
);
setInterval will call the function over and over again without needing to call setTimeout over and over again.
setInterval is what you want, as documented in W3C, you should pass a function and a time interval in milliseconds on how often to execute the code.
var counter = 0;
setInterval(function(){
counter = 1 - counter;
//Do what you want with the result...
//alert(counter);
}, 1000);
https://codepen.io/paulodiogo/pen/xPPOKa?editors=1010
Not using global variable...
https://codepen.io/paulodiogo/pen/KyyMXZ

Javascript for() not working

I am trying to make a progress bar with Javascript. I am using a for loop to run the code:
var prog = document.getElementById("progressbar").max;
var progg = document.getElementById("progressbar");
function runAnimation(){
for(var i=0; i < prog; i++){
var hit = progg.value;
hit++;
}
};
This should make the value of the progressbar increment each time the function runs, but it doesn't work. I am not getting any errors in the console. How can I make the progressbar's value rise incrementally?
For an "animated" effect, you can recursively call a setTimeout, based on the current value and max value of your progress bar. Something like:
var progg = document.getElementById("progressbar");
function runAnimation(){
setTimeout(function() {
if (progg.value <= progg.max) {
progg.value++;
runAnimation();
}
}, 10);
};
runAnimation();
Changing your timeout value (10 in the above example) will increase/decrease the progress bar.
Here's a fiddle: http://jsfiddle.net/cL7nygsr/
For a more interesting use of setTimeout (since the above is just basically setInterval), call it after an operation has completed before calling your next iteration. Here's an updated fiddle which includes a random update of the progress bar.
http://jsfiddle.net/cL7nygsr/2/
var b = document.getElementById('progress').max;
window.setInterval(a,1000);
function a() {
document.getElementById('progress').value++;
if (document.getElementById('progress').value >= b) {
window.clearInterval(a);
}
}
Here is code to increment progress bar value every 1 second, you can change to 2 second by replacing 1000 with 2000.
You're not doing anything with your hit variable once you increment it. You want to do this instead:
for (var i = 0; i < prog; i++) {
progg.value++;
}

Restart jQuery.each() after loop ends

I have array of values and i want to set those values as placeholders to my input.
How to achieve this using jQuery.each() only because i solved my issue with this solution and it works perfectly.
I tried doing this to restart it but it's not working:
if(index==arr.length) index=0;
HTML code:
Values : <input name='input' id='input' />
JS/jQuery code:
var arr = new Array();
for (var i = 0; i <= 5; i++) {
arr.push('Value ' + i);//fill array with values
}
function eachChange(){
var x=0;
$.each(arr, function (index, value) {
x++;
setTimeout(function(){
$('input').attr('placeholder', value);
}, x * 1000);
if(index==arr.length) index=0;
});
}
eachChange();//call function
Fiddle: http://jsfiddle.net/charaf11/5ZQgX/
There are two issues with trying to restart a .each() loop this way. First and foremost, that's not how .each() really works. It's less a loop and more shorthand for calling the function on every element. If you gave that anonymous function a name (let's go with setPlaceholder()), the .each() call is essentially doing this:
setPlaceholder(0, arr[0]);
setPlaceholder(1, arr[1]);
setPlaceholder(2, arr[2]);
setPlaceholder(3, arr[3]);
setPlaceholder(4, arr[4]);
setPlaceholder(5, arr[5]);
The index value it passes to the function isn't used for looping purposes, so trying to set it to 0 won't have any impact on the .each() call.
The second issue is your if condition. It'll never actually fire, since the final "iteration" of the .each() call will have arr.length - 1 as its value, not arr.length.
I'm not sure why you want to have it keep looping, but if that's your goal, you could accomplish it like this:
function eachChange(){
$.each(arr, function (index, value) {
setTimeout(function() {
$('input').attr('placeholder', value);
}, index * 1000);
if (index == arr.length - 1) {
setTimeout(eachChange, (index + 1) * 1000);
}
});
}
eachChange();//call function
What that should do is schedule eachChange() to be called again 1 second after the last placeholder update takes place. You can add in some other checks to limit the number of times it recurses, but if you want it to happen indefinitely that should do the trick.
Here's an updated fiddle demonstrating it.
you can compare the index with the arr.length like this
var arr = new Array();
for (var i = 0; i <= 5; i++) {
arr.push('Value ' + i);//fill array with values
}
function eachChange(){
$.each(arr, function (index, value) {
setTimeout(function(){
$('input').attr('placeholder', value);
//if it is the last element in arr setTimeout and call eachChange()
if(index>=arr.length-1){
setTimeout(function(){
eachChange();
},1000);
}
}, index * 1000);
});
}
eachChange();
http://jsfiddle.net/R274P/1/
I dont think you can reset the counter of the $.each function, as it seems to encapsulate a simple for loop. You dont have access to the counter from the outside.
However, try:
function eachChange(initX){
var x = initX || 0;
$.each(arr, function (index, value) {
x++;
setTimeout(function(){
$('input').attr('placeholder', value);
}, x * 1000);
// Call yourself but pass current x
if(index==arr.length) eachChange(x);
});
}
Remove the initX part if you want x to reset, but i assume you want it to keep counting from where the previous loop finished.

While loop only returning final result

while (counterInc < counter) {
window.setTimeout(function () {
$('#results').text(counterInc);
}, 3000);
counterInc++;
}
This code should increment the tag with ID results every 3000 milliseconds instead the while loop is running and returning the final result. For example instead of changing the text to 1, 2, 3, 4, 5,..n, it is changing the text to n. How would one have the loop update the text field every 1000 milliseconds with each increment instead of only the final result?
Try this
var counterInc = 0;
var counterMax = 10;
var timeoutId = window.setInterval(function() {
$('#results').text(counterInc++);
if (counterInc >= counterMax) {
window.clearInterval(timeoutId);
}
}, 500);​
http://jsfiddle.net/GufCs/4/
What was happening was you timeout updated the cell every three seconds, however, your loop can run through a ridiculous amount of numbers in 3 seconds, so it's long since complete by the time the function in setTimeout had run.
This will trigger the function every 500ms (change to 3000ms for your purposes) and only then will it increment the counterInc. Add it clears the Interval when it reaches counterMax.
The problem is that setTimeout() acts as an "independent thread". You set it and it executes once after the specified amount of time. In the mean time the "main thread" keeps running: so your counter will get increased in the meantime.
To understand the problem you need to understand what a closure is.
Here you want each time to pass a certain value not the one computed at the end of the loop scope.
So compute the value at the moment you declare the setTimout rather than when it is call you can do as follow: http://jsfiddle.net/lechevalierd3on/jhYm3/
var counter = 10;
var counterInc= 0;
while (counterInc < counter) {
window.setTimeout(function () {
var inc = counterInc;
return function(){
$('#results').text(inc);
}
}(counterInc), 1000 * counterInc);
counterInc++;
}​
while (counterInc < counter) {
window.setTimeout(function () {
$('#results').text(counterInc);
}, 3000 * counterInc++);
}

Categories