How to reset a p5.js sketch if it fails to load - javascript

hello i have a sketch which basically pulls from a giant database of over 8,000 images to select an image. sometimes, an image will fail to load and its not feasible for me to go through all 8000 images and find which ones are causing my sketch to freeze on "Loading..."
i just want a way to reset the sketch if the image selected fails to load and just select the next image or a random image or placeholder image in case one fails to load, instead of it just hanging on a "Loading..." screen.
seems like a really simple thing but i can't find any simple solution. i tried making a script to check if "p5_loading" div exists after a Timeout period, but then i realized since the sketch wont load if its broken then my Timeout will never run out to be able to check if it is broken.
thanks.

The bad news is that preload() and loadImage() have some serious shortcomings in this regard. The way preload() works is that when you have it declared, p5.js wraps all of the loadXXX() functions with a function that increments a counter before actually calling the underlying loadXXX() function. Each loadXXX() function then decrements the preload counter, but only if the resource is loaded successfully. As a result, unless one resorts to accessing p5.js internals, there is no way to re-try or recover from an error during preload.
Additionally loadImage() does not have good error handling logic. The issue is that loadImage() first performs an fetch() request for the resource, and if that does not raise an error it creates a Image object and uses its src property to actually load the image data. The problem with that is that it doesn't check the response status code and the Image object does not generate detailed error information. I would go so far as to call this a defect in p5.js worth of filing a GitHub issue. As a consequence, any robust loader that uses loadImage() has to treat all load failures equally (as opposed to an intelligent solution that would treat 5xx errors and timeouts as retry-able, but treat 4xx errors as not worth retrying).
So, given the bad news, what could we do? Roll our own loading screen and use the somewhat suboptimal error handling from loadImage():
const availableImages = [1, 2, 3, 4, 5];
const loading = {};
const loaded = [];
const size = 50;
const maxRetries = 3;
let isLoading = true;
function robustLoad(success, failure) {
// select a random image
let ix = floor(random(0, availableImages.length));
// remove that image from the list of available images
let id = availableImages.splice(ix, 1)[0];
console.log(`attempting to load image id ${id}`);
function tryLoadImage(retryCount) {
loading[id] = loadImage(
`https://robustp5jspreload.kumupaul.repl.co/get-image?id=${id}`,
() => {
// success
loaded.push(loading[id]);
delete loading[id];
success();
},
err => {
console.warn(`error loading image ${id}`);
console.log(err);
if (retryCount < maxRetries) {
console.log(`retrying image ${id}`);
tryLoadImage(retryCount + 1);
} else {
// throw in the towel on this id
delete loading[id];
if (availableImages.length > 0) {
robustLoad(success, failure);
} else {
failure();
}
}
}
);
}
tryLoadImage(0);
}
function setup() {
createCanvas(windowWidth, windowHeight);
background(200);
textSize(48);
textAlign(LEFT, TOP);
text('Loading...', 10, 10);
// attempt to load two random images
let status = [false, false];
for (let n = 0; n < 2; n++) {
let currentN = n;
robustLoad(
() => {
status[currentN] = true;
if (status.every(v => v)) {
// We're done loading.
isLoading = false;
drawBg();
loop();
}
},
() => {
console.warn(`unable to load image ${currentN}`);
}
);
}
}
function drawBg() {
let i = 0;
let j = 0;
for (let y = 0; y < height; y += size) {
for (let x = 0; x < width; x += size) {
image(loaded[i++ % loaded.length], x, y, size, size);
}
i = ++j;
}
}
function draw() {
if (!isLoading) {
circle(mouseX, mouseY, 30);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
Note: This example is not meant to be something you would just use as is. It is just an example of one possible implementation.
The source I'm loading image from is a proof of concept I made on Replit which returns 502 66% of the time. As a result it's theoretically that it will completely fail some percentage of the time.

Related

javascript load and show each image in loop

I'm new to javascript, and I've been stuck on this simple problem for days. I have a series of thousands of images (collectively a "dataset") that when viewed rapidly one after the other gives the appearance of video. I want to loop through all of my images.
I've created a function like so:
function updateImage(dataset, record_id) {
image_url = '/image?dataset='+dataset+'&record-id='+record_id;
if ($('#mpeg-image').length > 0) {
$('#mpeg-image')[0].src = image_url;
} else {
$("#image-thumbnail").html('<img id="mpeg-image", src="'+image_url+'"> </img>');
}
}
Calling the function once, e.g., updateImage('dataset_28_18-08-11',444); results in the image content updating in the browser. However, I want to show the images in a loop, so I created a function like this:
function playVideo() {
for (i = 0; i < 1800; i++) {
updateImage(dataset,i);
}
}
This function uses the same updateImage() function that worked above, but when I run playVideo(); Chrome doesn't update the image until the very end. The src tag changes, but the actual content does not. How can I alter my loop so that each image is loaded and shown in sequence? I don't want to use something like "Sprite" that merges all images into one, since that's too data intensive on my backend. I just want to load and show my images one after the other.
Browsers won't re-render page elements until there's a break in the execution of your code. Your entire image loop will run before the browser ever gets a chance to re-paint the images.
It's not because the loop "runs too fast" or because the images haven't loaded (though that can definitely pose problems). To see an example of redrawing issue, try changing your animation into an infinite loop, where it continually plays. The page will freeze ("pinwheel") forever and the page elements will never be updated, even long after all of your images have loaded. You need to give the browser an opportunity to redraw the page whenever you've made changes to page elements.
In web animation, this is often done via window.requestAnimationFrame() (see MDN docs). The method takes a callback function which is executed after the browser has redrawn the page. The browser will execute your callback once it's ready for page changes.
A simplistic example of this with you code would go something like this.
var imageNo = 0;
function step() {
updateImage(dataset, imageNo);
imageNo++;
if (imageNo < 1800) {
window.requestAnimationFrame(step);
}
}
window.requestAnimationFrame(step);
You can achieve a similar effect using setTimeout() or setInterval(), but those methods aren't optimized for animation.
The reason why you only see the last image is because of two things.
1. as #andriusain said, it takes the browser some indeterminate amount of time to download each image.
2. The loop runs so fast that the last iteration is what takes affect.
With that said, it would be best to either sprite the image (which it sounds like you can't do), or you can preload the images so that the browser caches them, then set the urls. You can do something like this.
// using es6
// I'd recommend adding <img src="mpeg-image" /> to your html page
// just to simplify the code. Also I recommend saving the image
// element in a local variable instead of using jQuery in each
// iteration loop which will definitely give a slower performance.
const mpegImgElement = $('#mpeg-image')[0];
const FPS = 30 / 1000; // 30 Frames Per Second
function playVideo() {
preLoadImages()
.then(urls => {
playUrls(urls);
})
.catch(error => {
console.log('error loading images', error);
})
}
function playUrls(urls) {
const index = 0;
const intervalId = setInterval(() => {
// set the url
mpegImgElement.src = urls[index];
// all done. stop the interval
if (++index === urls.length) {
clearInterval(intervalId);
}
}, FPS);
}
function preLoadImages() {
const promises = [];
for (i = 0; i < 1800; i++) {
const imageUrl = '/image?dataset='+dataset+'&record-id='+record_id;
const promise = loadImage(imageUrl);
promises.push(promise);
}
return Promise.all(promises);
}
function loadImage(url) {
return new Promise((resolve, reject) => {
const image = new Image();
image.addEventListener('load', () => {
resolve(url);
});
image.addEventListener('error', error => {
reject(error);
});
image.src = url;
});
}
This happens because the browser is still loading the images... I think your best bet is to programmatically load them first and once they are loaded then play the video... to do that maybe something like this will help:
var loadImages = function(images, callback) {
var loadTotal = 0;
for (var i = 0; i < images.length; i++) {
var image = new Image();
image.addEventListener('load', function() {
loadTotal++;
if (loadTotal === images.length) {
callback();
}
});
image.src = images[i];
}
}
var playVideo = function() {
// do stuff...
}
var images = ['image1.jpg', 'image2.jpg'];
loadImages(images, playVideo);
This idea is terrible.
JS is executed in single thread, while calling data from src is asynchronous method. Calling one by one and wait then definitely block the thread.
In this case you need promise to prepare all images first.
I make a workable example using google logo.
paths = ["https://www.google.com.hk/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png",
"https://www.google.com.hk/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png",
"https://www.google.com.hk/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"]
var imgCount = paths.length;
function loadImage(url) {
return new Promise((resolve, reject) => {
let img = new Image();
img.addEventListener('load', e => resolve(img));
img.src = url;
});
}
promises = []
for (var i = 0; i < paths.length; i++){
path = paths[i];
promises.push(loadImage(path));
}
Promise.all(promises).then(imgs => {
imgs.forEach(e => document.getElementById('image-holder').appendChild(e));});
//What I done here is display then all, but you can make it like, replace one by one, or declare your own display function.
<div id="image-holder"></div>

Report completion of recursive function in node.js

I'm building a web crawler in node.js and Electron.
Essentially, the program takes in a starting URL, and crawls through to a certain depth, reporting back where it found certain keywords.
This is working aso far, but I can't figure out how to actually tell when it's done. Given a depth of 3-4, this program seems to run forever. with a lower depth, the only way to really tell if it's still crawling is to look at the amount of CPU/memory it's using.
Here is the function that does the crawling:
function crawl(startingSite, depth) {
if (depth < maxDepth) {
getLinks(startingSite, function (sites) { //pulls all the links from a specific page and returns them as an array of strings
for (var i = 0; i < sites.length; i++) { //for each string we got from the page
findTarget(sites[i], depth); //find any of the keywords we want on the page, print out if so
crawl(sites[i], depth + 1); //crawl all the pages on that page, and increase the depth
}
});
}
}
My problem is, I can't figure out how to get this function to report back when it's done.
I tried something like this:
function crawl(startingSite, depth, callback) {
if (depth < maxDepth) {
getLinks(startingSite, function (sites) { //pulls all the links from a specific page and returns them as an array of strings
for (var i = 0; i < sites.length; i++) { //for each string we got from the page
findTarget(sites[i], depth); //find any of the keywords we want on the page, print out if so
crawl(sites[i], depth + 1); //crawl all the pages on that page, and increase the depth
}
});
}
else
{
callback();
}
}
but obviously, the callback() gets called immediately, because the crawler hits the depth quickly and exits the if statement.
All I need is for this function to print out (to the console.log for example) as soon as all the recursive instances of it are done crawling and have reached the maximum depth.
Any ideas?
You could use promises:
const links = (start) =>
new Promise(res => getLinks(start, res));
async function crawl(startingSite, depth) {
if (depth >= maxDepth)
return;
const sites = await links(startingSite);
for (const site of sites) {
await findTarget(site, depth);
await crawl(site, depth + 1);
}
}
Then just do:
crawl(something, 0).then(() => console.log("done"));

Javascript recursive function for banner pictures

I trying to create a rotating banner for cycle a few images.
const images = [url1, url2 url3]
const rotate = (url) => {
document.getElementById('banner').style.background = url
rotate(next)
}
Url's are correct full paths only shortened here in question. I'm striggl ing to solve how to get next in code above. This is some code I write from looking at examples. Im not a js programmer only recently started. Thank you for helping.
Here's one approach:
const rotate = (element, delay, urls) => {
let current = 0;
(function next() {
element.style.background = url[current]; // set image
current = (current + 1) % urls.length; // update for next pass
setTimeout(next, delay); // recycle
})(); // start immediately
};
with usage:
rotate(document.getElementById('banner'), 5000, [url1, url2, url3]);
The modulo arithmetic resets current to zero after the last image has been shown.

How to know when browser finish to process an image after loading it?

When an image object is created, can know when is fully loaded using the "complete" property, or the "onload" method, then, this image has processed ( resizing for example ) using some time, that can be some seconds in big files.
How to know when browser finish to process an image after loading it?
EDIT: In examples can see a lag between "complete" message and the appearance of the image, I want avoid this.
Example ussing "onload" method:
var BIGimage;
putBIGimage();
function putBIGimage(){
BIGimage=document.createElement("IMG");
BIGimage.height=200;
BIGimage.src="http://orig09.deviantart.net/5e53/f/2013/347/f/d/i_don_t_want_to_ever_leave_the_lake_district_by_martinkantauskas-d6xrdch.jpg";
BIGimage.onload=function(){waitBIGimage();};
}
function waitBIGimage(){
console.log("Complete.");
document.body.appendChild(BIGimage);
}
Example using "complete" property:
var BIGimage;
putBIGimage();
function putBIGimage(){
BIGimage=document.createElement("IMG");
BIGimage.height=200;
BIGimage.src="http://orig09.deviantart.net/5e53/f/2013/347/f/d/i_don_t_want_to_ever_leave_the_lake_district_by_martinkantauskas-d6xrdch.jpg";
waitBIGimage();
}
function waitBIGimage(){
if (!BIGimage.complete){
console.log("Loading...");
setTimeout(function(){
waitBIGimage();
},16);
} else {
console.log("Complete.");
document.body.appendChild(BIGimage);
}
}
EDIT: Thanks the #Kaiido's response I made this sollution for wait the images process.
var imagesList=["https://omastewitkowski.files.wordpress.com/2013/07/howard-prairie-lake-oregon-omaste-witkowski-owfotografik-com-2-2.jpg",
"http://orig03.deviantart.net/7b8d/f/2015/289/0/f/0ffd635880709fb39c2b69f782de9663-d9d9w6l.jpg",
"http://www.livandiz.com/dpr/Crater%20Lake%20Pano%2016799x5507.JPG"];
var BIGimages=loadImages(imagesList);
onLoadImages(BIGimages,showImages);
function loadImages(listImages){
var image;
var list=[];
for (var i=0;i<listImages.length;i++){
image=document.createElement("IMG");
image.height=200;
image.src=listImages[i]+"?"+Math.random();
list.push(image);
}
return list;
}
function showImages(){
loading.style.display="none";
for (var i=0; i<BIGimages.length;i++){
document.body.appendChild(BIGimages[i]);
}
};
function onLoadImages(images,callBack,n) {
if (images==undefined) return null;
if (callBack==undefined) callBack=function(){};
else if (typeof callBack!="function") return null;
var list=[];
if (!Array.isArray(images)){
if (typeof images =="string") images=document.getElementById(images);
if (!images || images.tagName!="IMG") return null;
list.push(images);
} else list=images;
if (n==undefined || n<0 || n>=list.length) n=0;
for (var i=n; i<list.length; i++){
if (!list[i].complete){
setTimeout(function(){onLoadImages(images,callBack,i);},16);
return false;
}
var ctx = document.createElement('canvas').getContext('2d');
ctx.drawImage(list[i], 0, 0);
}
callBack();
return true;
}
<DIV id="loading">Loading some big images...</DIV>
The HTMLImageElement interface has a decode() method, which does allow us to wait until the image is ready to be drawn, just like you want.
var BIGimage;
putBIGimage();
function putBIGimage() {
BIGimage = document.createElement("IMG");
BIGimage.height = 200;
BIGimage.src = "https://upload.wikimedia.org/wikipedia/commons/c/cf/Black_hole_-_Messier_87.jpg?r=" + Math.random();
BIGimage.onload = e => console.log('load event', performance.now());
BIGimage.decode().then(waitBIGimage);
BIGimage.onerror = console.error;
}
function waitBIGimage() {
// uses the synchronous testing method to check it works fine
var start = performance.now();
// only to see if it worked fine
var ctx = document.createElement('canvas').getContext('2d');
ctx.drawImage(BIGimage, 0, 0);
ctx.drawImage(ctx.canvas, 0, 0);
var end = performance.now();
console.log(`it took ${end - start}ms to draw`)
// do your stuff
document.body.appendChild(BIGimage);
}
Another way, is to use the fact that the CanvasContext2D drawImage method can be synchronous. Some browsers may try to delay the actual painting for the next painting frame, but by drawing the canvas onto itself we can force most of the current UAs to render our image synchronously.
So you can use it as a waiting method in your waitBIGimage method.
var BIGimage;
putBIGimage();
function putBIGimage() {
BIGimage = document.createElement("IMG");
BIGimage.height = 200;
BIGimage.src = "https://upload.wikimedia.org/wikipedia/commons/c/cf/Black_hole_-_Messier_87.jpg?r=" + Math.random();
BIGimage.onload = waitBIGimage;
BIGimage.onerror = console.error;
}
function waitBIGimage() {
// only for demo
// we've got to also log the time since even the console.log method will be blocked during processing
var start = performance.now();
console.log('waiting', start);
// this is all needed
var ctx = document.createElement('canvas').getContext('2d');
ctx.drawImage(BIGimage, 0, 0);
// on some system the drawing of the image may be delayed to the next painting frame
// we can try force the synchronous rendering by drawing the canvas over itself
ctx.drawImage(ctx.canvas, 0, 0);
// demo only
var end = performance.now();
console.log("Complete.", end);
console.log(`it took ${end - start}ms`)
// do your stuff
document.body.appendChild(BIGimage);
}
On my Firefox it takes about 1 second to process the image, while on my Chrome, it's a bit faster.
But one big issue with method is that it is synchronous, and thus will block your scripts during all the time the Image is processed.
Yet another way, is to use the createImageBitmap() method, which should allocate the image bitmap in the GPU, ready to be painted.
There is no reliable way to know - your browser can continue to execute arbitrary javascript or perform built in functions (i.e., resizing of the browser window) which can directly or indirectly affect the image and cause it to be either redrawn, or appear to not finish drawing for a while.
You can hook in to particular events in the lifetime of an image, but, strictly speaking, "finish" only happens when the browser window is closed.

DOM refresh on long running function

I have a button which runs a long running function when it's clicked. Now, while the function is running, I want to change the button text, but I'm having problems in some browsers like Firefox, IE.
html:
<button id="mybutt" class="buttonEnabled" onclick="longrunningfunction();"><span id="myspan">do some work</span></button>
javascript:
function longrunningfunction() {
document.getElementById("myspan").innerHTML = "doing some work";
document.getElementById("mybutt").disabled = true;
document.getElementById("mybutt").className = "buttonDisabled";
//long running task here
document.getElementById("myspan").innerHTML = "done";
}
Now this has problems in firefox and IE, ( in chrome it works ok )
So I thought to put it into a settimeout:
function longrunningfunction() {
document.getElementById("myspan").innerHTML = "doing some work";
document.getElementById("mybutt").disabled = true;
document.getElementById("mybutt").className = "buttonDisabled";
setTimeout(function() {
//long running task here
document.getElementById("myspan").innerHTML = "done";
}, 0);
}
but this doesn't work either for firefox! the button gets disabled, changes colour ( due to the application of the new css ) but the text does not change.
I have to set the time to 50ms instead of just 0ms, in order to make it work ( change the button text ). Now I find this stupid at least. I can understand if it would work with just a 0ms delay, but what would happen in a slower computer? maybe firefox would need 100ms there in the settimeout? it sounds rather stupid. I tried many times, 1ms, 10ms, 20ms...no it won't refresh it. only with 50ms.
So I followed the advice in this topic:
Forcing a DOM refresh in Internet explorer after javascript dom manipulation
so I tried:
function longrunningfunction() {
document.getElementById("myspan").innerHTML = "doing some work";
var a = document.getElementById("mybutt").offsetTop; //force refresh
//long running task here
document.getElementById("myspan").innerHTML = "done";
}
but it doesn't work ( FIREFOX 21). Then i tried:
function longrunningfunction() {
document.getElementById("myspan").innerHTML = "doing some work";
document.getElementById("mybutt").disabled = true;
document.getElementById("mybutt").className = "buttonDisabled";
var a = document.getElementById("mybutt").offsetTop; //force refresh
var b = document.getElementById("myspan").offsetTop; //force refresh
var c = document.getElementById("mybutt").clientHeight; //force refresh
var d = document.getElementById("myspan").clientHeight; //force refresh
setTimeout(function() {
//long running task here
document.getElementById("myspan").innerHTML = "done";
}, 0);
}
I even tried clientHeight instead of offsetTop but nothing. the DOM does not get refreshed.
Can someone offer a reliable solution preferrably non-hacky ?
thanks in advance!
as suggested here i also tried
$('#parentOfElementToBeRedrawn').hide().show();
to no avail
Force DOM redraw/refresh on Chrome/Mac
TL;DR:
looking for a RELIABLE cross-browser method to have a forced DOM refresh WITHOUT the use of setTimeout (preferred solution due to different time intervals needed depending on the type of long running code, browser, computer speed and setTimeout requires anywhere from 50 to 100ms depending on situation)
jsfiddle: http://jsfiddle.net/WsmUh/5/
Webpages are updated based on a single thread controller, and half the browsers don't update the DOM or styling until your JS execution halts, giving computational control back to the browser. That means if you set some element.style.[...] = ... it won't kick in until your code finishes running (either completely, or because the browser sees you're doing something that lets it intercept processing for a few ms).
You have two problems: 1) your button has a <span> in it. Remove that, just set .innerHTML on the button itself. But this isn't the real problem of course. 2) you're running very long operations, and you should think very hard about why, and after answering the why, how:
If you're running a long computational job, cut it up into timeout callbacks (or, in 2019, await/async - see note at the end of this anser). Your examples don't show what your "long job" actually is (a spin loop doesn't count) but you have several options depending on the browsers you take, with one GIANT booknote: don't run long jobs in JavaScript, period. JavaScript is a single threaded environment by specification, so any operation you want to do should be able to complete in milliseconds. If it can't, you're literally doing something wrong.
If you need to calculate difficult things, offload it to the server with an AJAX operation (universal across browsers, often giving you a) faster processing for that operation and b) a good 30 seconds of time that you can asynchronously not-wait for the result to be returned) or use a webworker background thread (very much NOT universal).
If your calculation takes long but not absurdly so, refactor your code so that you perform parts, with timeout breathing space:
function doLongCalculation(callbackFunction) {
var partialResult = {};
// part of the work, filling partialResult
setTimeout(function(){ doSecondBit(partialResult, callbackFunction); }, 10);
}
function doSecondBit(partialResult, callbackFunction) {
// more 'part of the work', filling partialResult
setTimeout(function(){ finishUp(partialResult, callbackFunction); }, 10);
}
function finishUp(partialResult, callbackFunction) {
var result;
// do last bits, forming final result
callbackFunction(result);
}
A long calculation can almost always be refactored into several steps, either because you're performing several steps, or because you're running the same computation a million times, and can cut it up into batches. If you have (exaggerated) this:
var resuls = [];
for(var i=0; i<1000000; i++) {
// computation is performed here
if(...) results.push(...);
}
then you can trivially cut this up into a timeout-relaxed function with a callback
function runBatch(start, end, terminal, results, callback) {
var i;
for(var i=start; i<end; i++) {
// computation is performed here
if(...) results.push(...); }
if(i>=terminal) {
callback(results);
} else {
var inc = end-start;
setTimeout(function() {
runBatch(start+inc, end+inc, terminal, results, callback);
},10);
}
}
function dealWithResults(results) {
...
}
function doLongComputation() {
runBatch(0,1000,1000000,[],dealWithResults);
}
TL;DR: don't run long computations, but if you have to, make the server do the work for you and just use an asynchronous AJAX call. The server can do the work faster, and your page won't block.
The JS examples of how to deal with long computations in JS at the client are only here to explain how you might deal with this problem if you don't have the option to do AJAX calls, which 99.99% of the time will not be the case.
edit
also note that your bounty description is a classic case of The XY problem
2019 edit
In modern JS the await/async concept vastly improves upon timeout callbacks, so use those instead. Any await lets the browser know that it can safely run scheduled updates, so you write your code in a "structured as if it's synchronous" way, but you mark your functions as async, and then you await their output them whenever you call them:
async doLongCalculation() {
let firstbit = await doFirstBit();
let secondbit = await doSecondBit(firstbit);
let result = await finishUp(secondbit);
return result;
}
async doFirstBit() {
//...
}
async doSecondBit...
...
SOLVED IT!! No setTimeout()!!!
Tested in Chrome 27.0.1453, Firefox 21.0, Internet 9.0.8112
$("#btn").on("mousedown",function(){
$('#btn').html('working');}).on('mouseup', longFunc);
function longFunc(){
//Do your long running work here...
for (i = 1; i<1003332300; i++) {}
//And on finish....
$('#btn').html('done');
}
DEMO HERE!
As of 2019 one uses double requesAnimationFrame to skip a frame instead of creating a race condition using setTimeout.
function doRun() {
document.getElementById('app').innerHTML = 'Processing JS...';
requestAnimationFrame(() =>
requestAnimationFrame(function(){
//blocks render
confirm('Heavy load done')
document.getElementById('app').innerHTML = 'Processing JS... done';
}))
}
doRun()
<div id="app"></div>
As an usage example think of calculating pi using Monte Carlo in an endless loop:
using for loop to mock while(true) - as this breaks the page
function* piMonteCarlo(r = 5, yield_cycle = 10000){
let total = 0, hits = 0, x=0, y=0, rsqrd = Math.pow(r, 2);
while(true){
total++;
if(total === Number.MAX_SAFE_INTEGER){
break;
}
x = Math.random() * r * 2 - r;
y = Math.random() * r * 2 - r;
(Math.pow(x,2) + Math.pow(y,2) < rsqrd) && hits++;
if(total % yield_cycle === 0){
yield 4 * hits / total
}
}
}
let pi_gen = piMonteCarlo(5, 1000), pi = 3;
for(let i = 0; i < 1000; i++){
// mocks
// while(true){
// basically last value will be rendered only
pi = pi_gen.next().value
console.log(pi)
document.getElementById('app').innerHTML = "PI: " + pi
}
<div id="app"></div>
And now think about using requestAnimationFrame for updates in between ;)
function* piMonteCarlo(r = 5, yield_cycle = 10000){
let total = 0, hits = 0, x=0, y=0, rsqrd = Math.pow(r, 2);
while(true){
total++;
if(total === Number.MAX_SAFE_INTEGER){
break;
}
x = Math.random() * r * 2 - r;
y = Math.random() * r * 2 - r;
(Math.pow(x,2) + Math.pow(y,2) < rsqrd) && hits++;
if(total % yield_cycle === 0){
yield 4 * hits / total
}
}
}
let pi_gen = piMonteCarlo(5, 1000), pi = 3;
function rAFLoop(calculate){
return new Promise(resolve => {
requestAnimationFrame( () => {
requestAnimationFrame(() => {
typeof calculate === "function" && calculate()
resolve()
})
})
})
}
let stopped = false
async function piDOM(){
while(stopped==false){
await rAFLoop(() => {
pi = pi_gen.next().value
console.log(pi)
document.getElementById('app').innerHTML = "PI: " + pi
})
}
}
function stop(){
stopped = true;
}
function start(){
if(stopped){
stopped = false
piDOM()
}
}
piDOM()
<div id="app"></div>
<button onclick="stop()">Stop</button>
<button onclick="start()">start</button>
As described in the "Script taking too long and heavy jobs" section of Events and timing in-depth (an interesting reading, by the way):
[...] split the job into parts which get scheduled after each other. [...] Then there is a “free time” for the browser to respond between parts. It is can render and react on other events. Both the visitor and the browser are happy.
I am sure that there are many times in which a task cannot be splitted into smaller tasks, or fragments. But I am sure that there will be many other times in which this is possible too! :-)
Some refactoring is needed in the example provided. You could create a function to do a piece of the work you have to do. It could begin like this:
function doHeavyWork(start) {
var total = 1000000000;
var fragment = 1000000;
var end = start + fragment;
// Do heavy work
for (var i = start; i < end; i++) {
//
}
Once the work is finished, function should determine if next work piece must be done, or if execution has finished:
if (end == total) {
// If we reached the end, stop and change status
document.getElementById("btn").innerHTML = "done!";
} else {
// Otherwise, process next fragment
setTimeout(function() {
doHeavyWork(end);
}, 0);
}
}
Your main dowork() function would be like this:
function dowork() {
// Set "working" status
document.getElementById("btn").innerHTML = "working";
// Start heavy process
doHeavyWork(0);
}
Full working code at http://jsfiddle.net/WsmUh/19/ (seems to behave gently on Firefox).
If you don't want to use setTimeout then you are left with WebWorker - this will require HTML5 enabled browsers however.
This is one way you can use them -
Define your HTML and an inline script (you don't have to use inline script, you can just as well give an url to an existing separate JS file):
<input id="start" type="button" value="Start" />
<div id="status">Preparing worker...</div>
<script type="javascript/worker">
postMessage('Worker is ready...');
onmessage = function(e) {
if (e.data === 'start') {
//simulate heavy work..
var max = 500000000;
for (var i = 0; i < max; i++) {
if ((i % 100000) === 0) postMessage('Progress: ' + (i / max * 100).toFixed(0) + '%');
}
postMessage('Done!');
}
};
</script>
For the inline script we mark it with type javascript/worker.
In the regular Javascript file -
The function that converts the inline script to a Blob-url that can be passed to a WebWorker. Note that this might note work in IE and you will have to use a regular file:
function getInlineJS() {
var js = document.querySelector('[type="javascript/worker"]').textContent;
var blob = new Blob([js], {
"type": "text\/plain"
});
return URL.createObjectURL(blob);
}
Setup worker:
var ww = new Worker(getInlineJS());
Receive messages (or commands) from the WebWorker:
ww.onmessage = function (e) {
var msg = e.data;
document.getElementById('status').innerHTML = msg;
if (msg === 'Done!') {
alert('Next');
}
};
We kick off with a button-click in this demo:
document.getElementById('start').addEventListener('click', start, false);
function start() {
ww.postMessage('start');
}
Working example here:
http://jsfiddle.net/AbdiasSoftware/Ls4XJ/
As you can see the user-interface is updated (with progress in this example) even if we're using a busy-loop on the worker. This was tested with an Atom based (slow) computer.
If you don't want or can't use WebWorker you have to use setTimeout.
This is because this is the only way (beside from setInterval) that allow you to queue up an event. As you noticed you will need to give it a few milliseconds as this will give the UI engine "room to breeth" so-to-speak. As JS is single-threaded you cannot queue up events other ways (requestAnimationFrame will not work well in this context).
Hope this helps.
Update: I don't think in the long term that you can be sure of avoiding Firefox's aggressive avoidance of DOM updates without using a timeout. If you want to force a redraw / DOM update, there are tricks available, like adjusting the offset of elements, or doing hide() then show(), etc., but there is nothing very pretty available, and after a while when those tricks get abused and slow down user experience, then browsers get updated to ignore those tricks. See this article and the linked articles beside it for some examples: Force DOM redraw/refresh on Chrome/Mac
The other answers look like they have the basic elements needed, but I thought it would be worthwhile to mention that my practice is to wrap all interactive DOM-changing functions in a "dispatch" function which handles the necessary pauses needed to get around the fact that Firefox is extremely aggressive in avoiding DOM updates in order to score well on benchmarks (and to be responsive to users while browsing the internet).
I looked at your JSFiddle and customized a dispatch function the one that many of my programs rely on. I think it is self-explanatory, and you can just paste it into your existing JS Fiddle to see how it works:
$("#btn").on("click", function() { dispatch(this, dowork, 'working', 'done!'); });
function dispatch(me, work, working, done) {
/* work function, working message HTML string, done message HTML string */
/* only designed for a <button></button> element */
var pause = 50, old;
if (!me || me.tagName.toLowerCase() != 'button' || me.innerHTML == working) return;
old = me.innerHTML;
me.innerHTML = working;
setTimeout(function() {
work();
me.innerHTML = done;
setTimeout(function() { me.innerHTML = old; }, 1500);
}, pause);
}
function dowork() {
for (var i = 1; i<1000000000; i++) {
//
}
}
Note: the dispatching function also blocks calls from happening at the same time, because it can seriously confuse users if status updates from multiple clicks are happening together.
Fake an ajax request
function longrunningfunction() {
document.getElementById("myspan").innerHTML = "doing some work";
document.getElementById("mybutt").disabled = true;
document.getElementById("mybutt").className = "buttonDisabled";
$.ajax({
url: "/",
complete: function () {
//long running task here
document.getElementById("myspan").innerHTML = "done";
}
});}
Try this
function longRunningTask(){
// Do the task here
document.getElementById("mybutt").value = "done";
}
function longrunningfunction() {
document.getElementById("mybutt").value = "doing some work";
setTimeout(function() {
longRunningTask();
}, 1);
}
Some browsers don't handle onclick html attribute good. It's better to use that event on js object. Like this:
<button id="mybutt" class="buttonEnabled">
<span id="myspan">do some work</span>
</button>
<script type="text/javascript">
window.onload = function(){
butt = document.getElementById("mybutt");
span = document.getElementById("myspan");
butt.onclick = function () {
span.innerHTML = "doing some work";
butt.disabled = true;
butt.className = "buttonDisabled";
//long running task here
span.innerHTML = "done";
};
};
</script>
I made a fiddle with working example http://jsfiddle.net/BZWbH/2/
Have you tried adding listener to "onmousedown" to change the button text and click event for longrunning function.
Slightly modified your code at jsfiddle and:
$("#btn").on("click", dowork);
function dowork() {
document.getElementById("btn").innerHTML = "working";
setTimeout(function() {
for (var i = 1; i<1000000000; i++) {
//
}
document.getElementById("btn").innerHTML = "done!";
}, 100);
}
Timeout set to more reasonable value 100ms did the trick for me. Try it.
Try adjusting the latency to find the best value.
DOM buffer also exists in default browser on android,
long running javascript only flush DOM buffer once,
use setTimeout(..., 50) to solve it.
I have adapted Estradiaz's double animation frame method for async/await:
async function waitForDisplayUpdate() {
await waitForNextAnimationFrame();
await waitForNextAnimationFrame();
}
function waitForNextAnimationFrame() {
return new Promise((resolve) => {
window.requestAnimationFrame(() => resolve());
});
}
async function main() {
const startTime = performance.now();
for (let i = 1; i <= 5; i++) {
setStatus("Step " + i);
await waitForDisplayUpdate();
wasteCpuTime(1000);
}
const elapsedTime = Math.round(performance.now() - startTime);
setStatus(`Completed in ${elapsedTime} ms`);
}
function wasteCpuTime(ms) {
const startTime = performance.now();
while (performance.now() < startTime + ms) {
if (Math.random() == 0) {
console.log("A very rare event has happened.");
}
}
}
function setStatus(s) {
document.getElementById("status").textContent = s;
}
document.addEventListener("DOMContentLoaded", main);
Status: <span id="status">Start</span>

Categories