Update number in same place on web page with javascript - javascript

Is there a way to make JavaScript print a counter continuously in the same place on the page?
for(var x=0; x<3000; x++){
document.write(x + '</br>');
document.body.innerHTML = "";
}
I want the number x to update and replace the previous number, however this code seems to wait until the loop is finished before showing a number (by then it is too late)
Is there a way to say, print number x, now wait 100ms, now clear and update in the same space the new value for x, and repeat?
(I know that the innerHTML is killing the whole page, for now all this pages needs to do is run a counter, so other elements are irrelevant. What I don't want is a printed list of all those numbers, and I need a delay)
Thanks!

The browser will not update the display while JavaScript is running. To make a timer happen you need to use setTimeout() or setInterval(). Also, avoid document.write() unless you have a good reason to use it (if you're not sure what makes a good reason then don't use it at all).
You want something like this:
<body>
<div id="counter"></div>
</body>
Then:
window.onload = function() {
var x = 0,
max = 3000,
ctr = document.getElementById("counter");
function incrementCounter() {
ctr.innerHTML = x;
if (x++ < max)
setTimeout(incrementCounter, 100);
}
incrementCounter();
}
Demo: http://jsfiddle.net/nnnnnn/v5hmE/
Note that the above updates only the contents of the "counter" div, so any other elements on your page would not be affected.
Homework assignment for you: Google everything you didn't understand in that code.

Yes! For that purpose I would recommend you two things:
To use a container (lets say a div) for that purpose:
and refer to it as document.getElementById('counter').innerHTML = x
To use javascript timers before updating.
Hope that helps,

...however this code seems to wait until the loop is finished before showing a number...
Don't use a for loop for this. You need a specific interval like you say. Use a function with a setTimeout and some recursion:
var x = 0;
var speed = 100;
function update() {
if (x <= 3000) {
setTimeout(function() {
// update DOM here
x++;
update();
}, speed);
} else {
return false;
}
}
Demo: http://jsfiddle.net/elclanrs/PRC9R/
You can change the interval to say 9 so it looks believable but goes faster.
x += 9; // instead of x++

Related

Why cant I scroll browser window in a loop in console?

I want to scroll down the browser window in a loop in console. I want it so that every time a scroll down (x)px down I stop, do something and then scroll (x)px again and then stop etc. until the page with ends (its a very long one, I want to parse info from it).
But when I started I stumbled upon an issue, that the scrolling function is executed only once, after the loop ends.
let i = 0;
scrollDownTillEnd = () => {
for(i; i<100; i++) {
window.scrollBy(0, 1000);
};
scrollDownTillEnd();
(it is a simplified example, but the idea should be clear)
I put the code in the console, being on a page I want to scroll, and get then the value of i at the end of the loop and only one scroll down.
Please, explain me, why this piece of code behaves like this and how to make it work, as I mentioned before (in every loop it scrolls a little bit).
Thank you!
Let me help address a few issues going on here.
1) You have an infinite loop going on because you are not checking that i is less than 100 even though you are incrementing it each time. You need to check that i < 100 so that the loop will eventually end. In your loop, 0 will always be less than 100 so the loop will never end.
2) You have a syntax error in your example because you're not actually closing out the scrollDownTillEnd function with a curly brace before calling the function itself.
3) Lastly, as good practice, you need to reset your i variable to 0 each time so that we can run this piece of code over and over again. The way you have it set up in your example, since i will be equal to 100 at the end of the first run, the loop won't ever run again after that until you reset i to 0 again. The easiest way to do this is to just initialize i to a value of 0 each time you execute this loop.
Try something like this:
scrollDownTillEnd = () => {
for(let i = 0; i < 100; i++) {
window.scrollBy(0, 1000);
};
};
scrollDownTillEnd();
You can use setInterval() since for loop will executes only once
function scrollDownTillEnd(countryDropdownList)
{
let scrollingInterval = setInterval(function(){
window.scrollBy(0,1000)
// write your condition
if (window.scrollHeight > 10000)
{
clearInterval(scrollingInterval)
}
},100)
}
scrollDownTillEnd();

Counting up using jquery

So far I have a little script that detects the scroll top position and at a set level I want it to trigger a jquery counter. So far I have an array with the maximum number inside var = eightyS = [3]; then there is..
if (y > 630) {
$('.targetS').each(function() {
//counter
delay(1000);
});
} else {
return false;
}
Now I've made something similar in C++ years ago (couldn't do it now with a gun to my head) so I followed a similar logic. But this is where I'm stuck. The idea behind this function is that it will do a read out on screen of 0 then 1 then 2 then 3. Any help is greatly appreciated
You could use a setInterval() which executes a function ever second such as below:
var count = 0;
var interval = setInterval(function(){
count++;
$('#counter').text(count);
}, 1000);
I've created a quick JSFiddle
You should be able to wrap this in to your code fairly easily. You may also want to use clearInterval(interval) to stop the function executing when you scroll back up the page; or when you get in to your else block, which would have the same effect. I've added a clearInterval() example to the JSFiddle on click of the stop link. You'll need to make sure the interval variable is in scope when clearing it.

javascript code hanging the page

I am trying to get the position of a moving div(animated using css3 animations) and for checking it continuously I am using a while(true) like below
function detectCollision(){
alert(document.getElementById("obstacle").style.left)
while(true){
var temp = getObstaclePosition();
var temp2 = getPlanePosition();
if(temp[0] <= temp2[0]+500){
document.getElementsByClassName("plane")[0].style.display = "none";
break;
}
}
}
The problem here is that after the first alert the page hangs. Moreover if I put an alert in the while loop then it keeps on popping up and the code works fine but not otherwise.
Let me know how I can fix this?
Instead of using a while (true), which is costly, you can use setInterval:
a = setInterval(function () {
var temp = getObstaclePosition();
var temp2 = getPlanePosition();
if(temp[0] <= temp2[0]+500){
document.getElementsByClassName("plane")[0].style.display = "none";
clearInterval(a);
}
}, 100);
The page does not render while you are inside that loop, and thus the position of the element will not change. This results in the loop never ending.
If you want to do something like this, you will have to be using a recursive setTimeout or a normal setInterval implementation.
With them, do one check per timeout.
https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout
JavaScript runs in one and the same thread, so if some loop occupies this with an infinite loop, the rest is not able to run anymore.
As an alternative to your loop, you could use setInterval, which repeatedly executes a function or code snippet:
setInterval(new function() {
// whatever
}, 100); // repeat every 100 ms, i.e. 10 times per second

how to stop moving background-image position

I've background image and by using small javascript code, it moves from right to left.
HTML code
<div id="clouds_image"></div>
Javascript code
var g=0;
var speed=30;
function rollClouds() {
document.getElementById('clouds_image').style.backgroundPosition=g+'px 0';
g--;
scroller=setTimeout(function(){rollClouds()},speed);
}
window.addEventListener?
window.addEventListener('load',rollClouds,false):
window.attachEvent('onload',rollClouds);
But i've noticed that, with time my PC CPU memory usage increased ! causing overload on my pc and if i disabled that javascript code, it back to normal.
My question
so i think i need to modify this javascript code that it not keep working forever, i mean, i want to make it to repeat that action only 5 times then stop , maybe i need to define value of g but i'm not good in javascript so any help ~ Thanks.
You need to use a variable to count how many times that function was executed, and use setInterval instead of setTimeout: See example
http://jsfiddle.net/EQDjx/206/ (my counter start from 100 and goes down to 0)
for a more nice effect i recomand you to use jquery. See animate function
http://api.jquery.com/animate/
var g = 1000;
var speed=300;
var counter = 100;
function rollClouds() {
document.getElementById('clouds_image').style.backgroundPosition=g+'px 0';
g--;
if (counter < 1) clearInterval(interval);
}
interval = setInterval(function(){rollClouds()}, speed)
A cleaner solution might be to use jQuery to move the background:
function moveClouds() {
$("#clouds_image").css({left:"-2000px"});
$("#clouds_image").animate({left:"2000px"},10000);
}
Then you might set an interval to trigger it every x milliseconds.
setInterval(moveClouds,10000)
JSFiddle is here: http://jsfiddle.net/qXpVX/

for loop delay in javascript

How to set delay in for loop execution
for(i=0; i<=10;i++){
var s=i;//This line should execute for every 2 secs only
}
How to give loop delay in java script....
I dont want like below..I want without using setTimeout...
for(i=0; i<=10;i++){
setTimeout("setvalue()",2000); //This alert should display for every 2 secs only
}
function setvalue()
{
var s=i;
}
please help me...
Use setInterval()
var i = 0;
var interval = setInterval(function(){
setValue();
i += 1;
if(i == 10)
clearInterval(interval);
}, 2000);
There is no way to sleep for 2sec without freezing the whole browser. Javascript is single threaded.
You can't. JS runs in a single thread and any attempt to delay that thread will freeze the entire page. Using setTimeout is your only option.
EDIT: or setInterval; either way, there is no non-hairy way to express "halt execution here for x milliseconds."
Using setTimeout is inevitable, however, a recursive function might be a better solution for this one:
var i=0;
function recurs() {
i = s;
i++;
if (i <= 10) recurs();
}
recurs();
As others have stated, setTimeout can be used very well to handle these sorts of scenarios and setInterval could also be used but is discouraged by some.
You can even recursively call a function that has setTimeout built into it as mentioned in the MDN documentation of setInterval. The heading there mentions 'dangerous usage' but their solution to the danger is the block of code beneath.
There it mentions that to have a loop executing every x seconds (or milliseconds) then you can do the following and know for sure that the functions will only be executing one at a time and in-sequence:
(function loop(){
setTimeout(function(){
// logic here
// recurse
loop();
}, 1000); // repeat loop 1 second after this branch has completed
})();
And if you want it to only do that a limited number of times, then you can create a variable outside of the loop and only recursively execute if the count is smaller than the number of times you want to execute for. Such as this:
var count = 0;
(function loop() {
setTimeout(function() {
// logic
count++;
if (count < 10) {
loop();
}
}, 1000);
})();

Categories