How to change instanly a DOM element? - javascript

I know that this might be a stupid question but it drives me crazy. I'm trying to change the innerHTML of a DOM element but it doesn't change until the end of the function's execution. For example:
function test(){
let testEl = document.getElementById('testEl')
for (let i = 0; i < 5; i++)
{
testEl.innerHTML = 'Count: ' + i;
alert(i);
}
}
Even if I have put an alert in the loop, the text of the element will not change until the end of the function's execution. How can the change be applied instantly (for example I mean during the loop)?

You can update the number every period of time using setInterval:
function test(){
let testEl = document.getElementById('testEl');
let i = 0;
const interval = setInterval(function(){
testEl.innerHTML = `Count: ${i++}`;
if(i === 5)
clearInterval(interval);
}, 1000);
}
test();
<p id="testEl"></p>

JavaScript runs in a single-threaded environment. This means that only one execution context can ever be running at any single point in time. Asynchronous code executes outside of the JavaScript runtime environment (in this case by the browser's native processing) and only when the JavaScript thread is idle can the results of an asynchronous request be executed (i.e. callbacks).
Below is an example that updates a DOM element approximately every second, creating a clock. However, if you click the button, it will ask the browser to render an alert, which is handled outside of the JavaScript runtime and is a blocking UI element, so the clock will stop. Once you clear the alert, you will see the time jump to be roughly current.
As you'll see, the asynchronous API call to window.setInterval() allows for the function to run repeatedly, every so often, and therefore not continuously. This replaces the need for a loop that runs in its entirety every time its accessed. Because of this, you can see updates to the webpage instead of the last value of your loop.
See the comments for more details:
const clock = document.querySelector("span");
// setInterval is not JavaScript. It's a call to a browser
// API asking the JS runtime to run the supplied function every
// 900 milliseconds, but that's just a request. After 900
// milliseconds, the browser will place the function on the
// JavaScript event queue and only when the JavaScript thread
// is idle will anything on the queue be executed. This is why
// the 900 milliseconds is not a guarantee - - it's just the
// minimum amount of time you'll have to wait for the function
// to run, but it could be longer if what's already running
// on the JavaScript thread takes longer than 900 milliseconds
// to complete.
window.setInterval(function(){
// Update the DOM
clock.textContent = new Date().toLocaleTimeString();
}, 900);
document.querySelector("button").addEventListener("click", function(){
// An alert is also not JavaScript, but another browser API that is executed
// by the browser, not JavaScript. However, it is a blocking (modal) UI element.
// The rest of the browser interface (including the web page) cannot update
// while the alert is present. As soon as the alert is cleared, the UI will update.
window.alert("I'm a UI blocking construct rendered by the browser, not JavaScript");
});
<div>Current time is: <span></span></div>
<button>Click for alert</button>

Another way to achieve it is by using async - Promise like this
async function test() {
let testEl = document.getElementById('testEl')
for (let i = 0; i < 5; ++i) {
testEl.innerHTML = 'Count: ' + i;
await new Promise((resolve, _) => {
setTimeout(function() {
resolve("");
}, 1000 /* your preferred delay here */);
});
}
}

Related

Function / setInterval unexpectedly logging twice to the console

I'm trying to create a callback to my Web API to collect new race data, I've created a setInterval and tested it to see if it does log to the console once as I would expect but for some reason the console is logging twice. I don't understand why.
I am wanting to remove the console.log() inside the if statement and replace that with a call to the server but if it's logging twice i'll receive twice as much information.
var TimeOutID = '';
var TenRaces = 0;
var StartThis = function () {
console.log("Starting run");
//Simulate counting down to next race
TimeOut = new Date().getTime() + 5000;
$('#next').countdown(TimeOut, function (event) {
$(this).html(event.strftime('%H:%M:%S'));
if(event.elapsed) {
//once the countdown timer has elapsed fetch data
console.log("Race: " + TenRaces); // <-- this one is logged twice
}
});
//loop ten races simulating ten different times data is needed
TenRaces++;
if (TenRaces > 10) {
clearInterval(TimeOutID);
}
};
TimeOutID = setInterval(StartThis, 6000);
Why is console.log() running and logging twice?
I'm using the jQuery plugin from http://hilios.github.io/jQuery.countdown/
According to the documentation, the elapsed mode is deliberately designed to continue after the countdown has finished. Therefore I think it's looping twice before the TenRaces var iterates. It would just keep logging forever if you didn't iterate that var.
Do the log/fetch data on the finish.countdown event instead, this triggers just once, when the countdown finishes. See documentation:
countdown documentation
E.g.
$('div#clock').countdown(finalDate)
.on('finish.countdown', callback);

setInterval works then hangs browser javascript

I'm wanting to animate an element using setInterval. I've put my code into an object with 2 functions one to initialize and one to animate using setInterval. When I try to run the code the animation works once then causes the browser to hang. The only thing I can think of is an infinite loop being created somewhere however I can't see anywhere in my code that would cause this.
What is causing the browser to crash, how can this be overcome ?
<div id='box' style='position:absolute;height:100px;width:100px;background-color:#44e'>box</div>
<script>
var box = {
init : function(elemId) {
box.elem = document.getElementById(elemId);
box.timer = setInterval;
box.tick = 0;
box.animate();
},
animate: function() {
if(box.tick < 100) {
box.elem.style.top = box.tick +'px';
box.elem.style.left = box.tick +'px';
box.tick++;
} else {
clearInterval(box.timer);
}
var timer = setInterval(box.animate, 50)
}
}
box.init('box');
</script>
setInterval sets up a function that will be called repeatedly by the browser until you cancel the interval timer. Your code isn't doing that, because the only call to clearInterval is using box.timer, which is never set to a timer handle (the return value from setInterval). So you end up scheduling thousands of calls (a new series every time animate is called) and bringing the browser to its kneeds.
At the very least, this:
var timer = setInterval(box.animate, 50)
should probably be:
box.timer = setInterval(box.animate, 50);
Or you may want setTimeout (which schedules only one call back).

How do I tell javascript to immediately update the DOM?

I am trying to load a 'loading' message to the user before a time-intensive function is called in javascript.
HTML:
<p id='foo'>Foo</p>​
Javascript:
var foo = document.getElementById('foo');
function tellViewerLoading() {
// Tell the user that loading is occuring.
foo.innerHTML = 'loading...';
}
function someActionThatTakesALongTime() {
// Do some action that takes a long time.
var i = 0;
while(i < 100000) {i++; console.log(i);};
}
function domUpdateDelayExperiment() {
tellViewerLoading();
someActionThatTakesALongTime();
}
domUpdateDelayExperiment();
JSFiddle: http://jsfiddle.net/johnhoffman/xDRVF/
What I want to happen is for the DOM to be updated immediately after tellViewerLoading() is called.
Instead, what happens is that the DOM seems to be updated after someActionThatTakesALongTime() finishes running. At that point, it is useless to display a loading message.
How do I tell javascript to immediately update the DOM after tellViewerLoading() is called?
Spawn the long-time running function with setTimeout:
function domUpdateDelayExperiment() {
tellViewerLoading();
setTimeout(someActionThatTakesALongTime, 50);
}
Explanation: the tellViewerLoading() function updates the DOM but the browser won't reflect changes on screen until domUpdateDelayExperiment() returns. By delaying someActionThatTakesALongTime by means of setTimeout() we let the browser to reflect DOM changes. The timeout is arbitrary, but its minimum value may be important in some browsers. A value of 50 ms is fair enough.
Actually, if you step through your code using a debugger, you will see that the loading text is changed before the next function is called.
Your browser is just hanging at the long function call, so it can't change the displayed text.
Using a short timeout can help if you want your browser to have enough time to change the display before going to the next function.

Show javascript execution progress

I have some javascript functions that take about 1 to 3 seconds. (some loops or mooML templating code.)
During this time, the browser is just frozen. I tried showing a "loading" animation (gif image) before starting the operation and hiding it afterwords. but it just doesnt work. The browser freezes before it could render the image and hides it immediately when the function ends.
Is there anything I can do to tell the browser to update the screen before going into javascript execution., Something like Application.DoEvents or background worker threads.
So any comments/suggestions about how to show javascript execution progress. My primary target browser is IE6, but should also work on all latest browsers
This is due to everything in IE6 being executed in the same thread - even animating the gif.
The only way to ensure that the gif is displayed prior to starting is by detaching the execution.
function longRunningProcess(){
....
hideGif();
}
displayGif();
window.setTimeout(longRunningProcess, 0);
But this will still render the browser frozen while longRunningProcess executes.
In order to allow interaction you will have to break your code in to smaller fragments, perhaps like this
var process = {
steps: [
function(){
// step 1
// display gif
},
function(){
// step 2
},
function(){
// step 3
},
function(){
// step 4
// hide gif
}
],
index: 0,
nextStep: function(){
this.steps[this.index++]();
if (this.index != this.steps.length) {
var me = this;
window.setTimeout(function(){
me.nextStep();
}, 0);
}
}
};
process.nextStep();
Perhaps you can put in a delay between showing the animated gif and running the heavy code.
Show the gif, and call:
window.setTimeout(myFunction, 100)
Do the heavy stuff in "myFunction".
You have to use a little more sophisticated technique to show the progress of the long running function.
Let's say you have a function like this that runs long enough:
function longLoop() {
for (var i = 0; i < 100; i++) {
// Here the actual "long" code
}
}
To keep the interface responsive and to show progress (also to avoid "script is taking too long..." messages in some browsers) you have to split the execution into the several parts.
function longLoop() {
// We get the loopStart variable from the _function_ instance.
// arguments.callee - a reference to function longLoop in this scope
var loopStart = arguments.callee.start || 0;
// Then we're not doing the whole loop, but only 10% of it
// note that we're not starting from 0, but from the point where we finished last
for (var i = loopStart; i < loopStart + 10; i++) {
// Here the actual "long" code
}
// Next time we'll start from the next index
var next = arguments.callee.start = loopStart + 10;
if (next < 100) {
updateProgress(next); // Draw progress bar, whatever.
setTimeout(arguments.callee, 10);
}
}
I haven't tested this actual code, but I have used this technique before.
Try setting a wait cursor before you run the function, and removing it afterwards. In jQuery you can do it this way:
var body = $('body');
body.css("cursor", "wait");
lengthyProcess();
body.css("cursor", "");

how many javascript setTimeout/ setInterval call can be set simultaneously in one page?

I have to use atleast 2 setTimeouts and 1 setInterval. Does this have any dependency on the browser or javascript engine being used?
tl;dr: Don't worry about the cost of timers until you're creating 100K's of them.
I just did a quick test of timer performance by creating this test file (creates 100K timers over and over):
<script>
var n = 0; // Counter used to verify all timers fire
function makeTimers() {
var start = Date.now();
for (var i = 0; i < 100000; i++, n++) {
setTimeout(hello, 5000);
}
console.log('Timers made in', Date.now() - start, 'msecs');
}
function hello() {
if (--n == 0) {
console.log('All timers fired');
makeTimers(); // Do it again!
}
}
setTimeout(makeTimers, 10000); // Wait a bit before starting test
</script>
I opened this file in Google Chrome (v54) on my circa ~2014 Macbook Pro, and went to the Timeline tab in Developer Tools and recorded the memory profile as the page loaded and ran thru 3-4 cycles of the test.
Observations
The timer creation loop takes 200ms. The page heap size starts at 3.5MB pre-test, and levels out at 3.9MB.
Conclusion
Each timer takes ~.002 msecs to set up, and adds about 35 bytes to the JS heap.
On a page you can have as many setTimeouts/setIntervals running at once as you wish, however in order to control each individually you will need to assign them to a variable.
var interval_1 = setInterval("callFunc1();",2000);
var interval_2 = setInterval("callFunc2();",1000);
clearInterval(interval_1);
The same code above applies to setTimeout, simply replacing the wording.
As Kevin has stated, JavaScript is indeed single threaded, so while you can have multiple timers ticking at once, only one can fire at any one time - i.e. if you have one that fires a function which 'halts' in execution, for example with an alert box, then that JS must be 'resumed' before another can trigger I believe.
One further example is given below. While the markup is not valid, it shows how timeouts work.
<html>
<body>
<script type="text/javascript">
function addThing(){
var newEle = document.createElement("div");
newEle.innerHTML = "Timer1 Tick";
document.body.appendChild(newEle);
}
var t1= setInterval("addThing();",1000);
var t2 = setInterval("alert('moo');",2000);
</script>
</body>
</html>
You can use as many as you want. Just remember that JavaScript is single threaded, so none of them can execute in parallel.
var interval_1 = setInterval("callFunc1();",2000); calls eval() which is evil so it's BAD.
Use this instead var interval_1 = setInterval(callFunc1,2000);
And for the question, you may use as many as you want but if all have the same interval between two actions, you better do it this way
var interval = setInterval(function() {
// function1
fct1();
// function2
fct2();
},2000);

Categories