How to call JQuery .each() iteration recursively - javascript

I am maintaining software that unfortunatelly has to run on IE8. The problem with IE8 is that it throws the 'script unresponsive' error if the synchronouse execution is too long:
This message displays when Internet Explorer reaches the maximum number of synchronous instructions for a piece of JavaScript. as described here
The standard way of dealing with this is something like
setTimeout(function(){ //slow code }, 1);
but, in my case the slow part is actually:
jQuery(/*selectors*/).each()// iteration
How can I terate through the elements found with jQuery().each(), where the actual .each() part is carried out recursively with timeouts? Even if the each() block does nothing I still get the pop-up warning. There is about 20,000 elements to iterate through... I know...
What is the best way to do it without rewriting anything on the page (let's assume I really can't rewrite the 20,000 elements table).

FYI, if your problem actually occurs because this operation all by itself:
jQuery(selectors)
takes too long, then you will have to change the selector to be something that is much faster to evaluate or change the HTML somehow so you can query for pieces of the table at a time. jQuery in IE8 is likely using the Sizzle library to evaluate the selector so if you've got a combination of large HTML, selector and Sizzle that are just too slow for IE8, then you will have to change one of the three.
We can't help with specifics on this issue without seeing the actual HTML and probably having some sort of test bed to experiment with. My guess would be that there could be a better selector, perhaps using natively supported query mechanisms such as getElementsByTagName() or something like that, but we'd have to see that actual HTML to make a more concrete recommendation. As you already know 20,000 elements in a really slow browser is just a bad recipe to start with.
If you get through the selector find and just want help with the iteartion, you can't use .each() directly because it will run all at once. Instead, you will have to manually iterate the jQuery list of DOM objects.
function processLargeArray(items) {
// set check size to whatever number of items you can process at once
var chunk = 100;
var index = 0;
function doChunk() {
var cnt = chunk;
while (cnt-- && index < items.length) {
// process items.eq(index) here
++index;
}
if (index < items.length) {
// set Timeout for async iteration
setTimeout(doChunk, 1);
}
}
doChunk();
}
var data = jQuery(selectors);
processLargeArray(data);
FYI, this code is adapted for use with a jQuery object from a more general purpose answer on the subject: Best way to iterate over an array without blocking the UI
And here's a version that uses a jQuery plugin to create a similar interface to .each() (but it's async).
jQuery.fn.eachChunk = function(chunk, eachFn, completeFn) {
var index = 0;
var obj = this;
function next() {
var temp;
if (index < obj.length) {
temp = obj.slice(index, index + chunk);
temp.each(eachFn);
index += chunk;
setTimeout(next, 1);
} else {
if (completeFn) {
completeFn();
}
}
}
next();
return this;
};
jQuery(selectors).eachChunk(100, yourFn);

I really like the Async Library:
https://github.com/caolan/async
which gives you a whole bunch of options of running sequential, asynchronous functions.
async.each([..], function(callback){
// Iterator function
callback();
});
Works in the same way as jQuery's each, but unlike jQuery, you get more control, such as:
async.eachSeries([...], function(callback){
// Will handle each element one at a time
callback();
});
And async.eachLimit, which means you cancontrol the number of tasks being run at any given time -so that x number of tasks are being run in parallel at any given time;
So, for example:
async.eachLimit([...], 2, function(callback){
// This will run the tasks simultaneously
callback();
});
Will run the iterator functions over all the elements in the array, but will limit the number of concurrently running tasks to 2. If you want 4 tasks, just change the second argument to 4, etc...
So, for example:
async.eachLimit([...], 2, function(callback){
// This will run up to 2 tasks simulatenously
callback(); // If successfull
});
If you need a timeout to make the operation fail silently after a timeout (jobs that pass the time out just don't get finished, and the rest of the queue moves on.
async.eachLimit([...], 2, function(callback){
// This will run up to 2 tasks simulatenously
callback(); // If successfull
setTimeout(function(){
return callback();
}, timeoutLength);
});
If you need a timeout to make the operation fail un-silently, (if there's one error, everything will stop).
async.eachLimit([...], 2, function(callback){
// This will run up to 2 tasks simulatenously
callback(); // If successfull
setTimeout(function(){
return callback("Error");
}, timeoutLength);
});
I'm not sure what the exact requirements of your job are, but I think the async library is a good candidate for this kind of stuff, and has a lot of control flow flexibility to get your job done.

This is one jQuery's way using each loop:
(function () { //avoid global var for test
var $elems = $('selector'), // elements to iterate
chunk = 50; //number of elements before stoping iteration
(function doStuff() { //recursive method
$elems.each(function (i) {
//delaying method when needed
if (i && !(i%chunk)) {
$elems = $elems.slice(i);
setTimeout(doStuff, 1);
return false;
}
//do slow stuff HERE
//...
});
})();
})();

Related

How to execute a function in Javascript with a delay and a flag condition (event handler-like)?

I'm writing a program in Javascript that takes input strings and then runs a simulation on each string. The user decides how fast, i.e. what the delay should be between processing each string. I'm using the setInterval() function to control this. However, I am running into the issue that longer strings may not be ready to process because the last string is still processing. This causes a slew of errors on my part. Here's some code to paint a better picture.
let testingInterval = setInterval(function () {
strprn.innerHTML = `<h2>${strings[i]}<\h2>`; // displays current string to user
if (i + 1 == strings.length) { // checks if should notify user all strings have been processed
checker.finalCheck = true;//the checker uses this flag to notify the user once the test completes
}
checker.check(strings[i]); //runs the check i.e. simulation
i++; // increments the counter iterating through the array (setup code not shown here)
if (i >= strings.length) {
clearInterval(testingInterval); //once we reach the end stop the interval iterating
evenOutResults(); // clean up answers function
updateTimeStamp(Date.now()); // for readability, I add a timestamp of when the results were generated
}
}, delay); // user specified delay
What I'm looking for is a way to honor the delay but also not begin the next call until the current string has finished processing.
Something like this logically (the code below freezes your browser XD):
function delayLoop() {
setTimeout(function () {
strprn.innerHTML = `<h2>${strings[i]}<\h2>`;
if (i + 1 == strings.length){
checker.finalCheck = true;
}
checker.check(strings[i]);
i++;
if (i < strings.length) {
// check if the current string has finished, if so call, else wait until the string is done
while (checker.processingFlag){
// console.log('Waiting for current string to finish');
}
delayLoop(); // call again
} else {
evenOutResults();
updateTimeStamp(Date.now());
}
}, delay);
Correct me if I'm wrong, but it seems like as though you want to have some kind of schedule of appointments that you'd like "messages" to be received at and if a message is not ready at the appointment, then you'd like it to reschedule to the next appointment. You can easily find the next available appointment with some kind of iteration
const nextCheckin = (lastCheckin, interval) => {
while (lastCheckin < Date.now())
last += delay
return last
}
Assuming the order of messages matters you can do something like such
const simulation = (strings, delay) => {
let checkin = Date.now() + delay
for (const str of strings) {
const result = simulate(str)
checkin = nextCheckin(checkin, delay)
console.log(`Waiting for: ${checkin-Date.now()}`)
while (Date.now() < checkin)
continue
reportWork(result)
}
}
The while loop will cause the event loop to hang, so maybe a call to setTimeout would be more appropriate, but whatever floats a boat.
Sorry, I should have clarified this more. Checker.check() is a function that uses a setInterval() to display an animation. The animation needs to be done for a set of objects. Because of the setInterval(), anytime we wait means javascript will try to execute the next lines of code. This means vanilla for-loops are out of the question.
My initial solution was to throw the for-loop iteration itself into a setTimeout(). This works as long as the delay is long enough for all the objects being iterated. Problem is the objects rarely are, so if an object was larger than the one it preceded and the delay was short then the whole animation crashed. In the end, Promises were the easiest solution.
let runLoop = async () => {
for(var i = 0; i < strings.length; i++){
strprn.innerHTML = `<h2>${strings[i]}<\h2>`;
console.log("about to await");
if (i + 1 == strings.length){
checker.finalCheck = true;
}
await new Promise(resolve => checker.check(resolve, strings[i]));
if (checker.finalCheck){
updateTimeStamp(Date.now());
}
}
}
runLoop();
For those who wonder onto this looking for an answer, the await pauses your execution until the resolve is met. You pass resolve onto your function, and inside the setInterval() code block, at the very end you call resolve(). In order to use the await, the whole thing gets wrapped up inside of an async.

Animations under single threaded JavaScript

JavaScript is a single threaded language and therefore it executes one command at a time. Asynchronous programming is being implemented via Web APIs (DOM for event handling, XMLHttpRequest for AJAX calls, WindowTimers for setTimeout) and the Event queue which are managed by the browser. So far, so good! Consider now, the following very simple code:
$('#mybox').hide(17000);
console.log('Previous command has not yet terminated!');
...
Could someone please explain to me the underlying mechanism of the above? Since .hide() has not yet finished (the animation lasts 17 seconds) and JS engine is dealing with it and it is capable of executing one command at a time, in which way does it go to the next line and continues to run the remaining code?
If your answer is that animation creates promises, the question remains the same: How JavaScript is dealing with more than one thing at the same time (executing the animation itself, watching the animation queue in case of promises and proceeding with the code that follows...).
Moreover, I cannot explain how promises in jQuery work if they have to watch their parent Deferred object till it is resolved or rejected that means code execution and at the same time the remaining code is executed. How is that possible in a single threaded approach? I have no problem to understand AJAX calls for I know they are taken away from JS engine...
tl;dr; it would not be possible in a strictly single threaded environment without outside help.
I think I understand your issue. Let's get a few things out of the way:
JavaScript is always synchronous
No asynchronous APIs are defined in the language specification. All the functions like Array.prototype.map or String.fromCharCode always run synchronously*.
Code will always run to completion. Code does not stop running until it is terminated by a return, an implicit return (reaching the end of the code) or a throw (abruptly).
a();
b();
c();
d(); // the order of these functions executed is always a, b, c, d and nothing else will
// happen until all of them finish executing
JavaScript lives inside a platform
The JavaScript language defines a concept called a host environment:
In this way, the existing system is said to provide a host environment of objects and facilities, which completes the capabilities of the scripting language.
The host environment in which JavaScript is run in the browser is called the DOM or document object model. It specifies how your browser window interacts with the JavaScript language. In NodeJS for example the host environment is entirely different.
While all JavaScript objects and functions run synchronously to completion - the host environment may expose functions of its own which are not necessarily defined in JavaScript. They do not have the same restrictions standard JavaScript code has and may define different behaviors - for example the result of document.getElementsByClassName is a live DOM NodeList which has very different behavior from your ordinary JavaScript code:
var els = document.getElementsByClassName("foo");
var n = document.createElement("div");
n.className = "foo";
document.body.appendChild(n);
els.length; // this increased in 1, it keeps track of the elements on the page
// it behaves differently from a JavaScript array for example.
Some of these host functions have to perform I/O operations like schedule timers, perform network requests or perform file access. These APIs like all the other APIs have to run to completion. These APIs are by the host platform - they invoke capabilities your code doesn't have - typically (but not necessarily) they're written in C++ and use threading and operating system facilities for running things concurrently and in parallel. This concurrency can be just background work (like scheduling a timer) or actual parallelism (like WebWorkers - again part of the DOM and not JavaScript).
So, when you invoke actions on the DOM like setTimeout, or applying a class that causes CSS animation it is not bound to the same requirements your code has. It can use threading or operating system async io.
When you do something like:
setTimeout(function() {
console.log("World");
});
console.log("Hello");
What actually happens is:
The host function setTimeout is called with a parameter of type function. It pushes the function into a queue in the host environment.
the console.log("Hello") is executed synchronously.
All other synchronous code is run (note, the setTimeout call was completely synchronous here).
JavaScript finished running - control is transferred to the host environment.
The host environment notices it has something in the timers queue and enough time has passed so it calls its argument (the function) - console.log("World") is executed.
All other code in the function is run synchronously.
Control is yielded back to the host environment (platform).
Something else happens in the host environment (mouse click, AJAX request returning, timer firing). The host environment calls the handler the user passed to these actions.
Again all JavaScript is run synchronously.
And so on and so on...
Your specific case
$('#mybox').hide(17000);
console.log('Previous command has not yet terminated!');
Here the code is run synchronously. The previous command has terminated, but it did not actually do much - instead it scheduled a callback on the platform a(in the .hide(17000) and then executed the console.log since again - all JavaScirpt code runs synchronously always.
That is - hide performs very little work and runs for a few milliseconds and then schedules more work to be done later. It does not run for 17 seconds.
Now the implementation of hide looks something like:
function hide(element, howLong) {
var o = 16 / howLong; // calculate how much opacity to reduce each time
// ask the host environment to call us every 16ms
var t = setInterval(function
// make the element a little more transparent
element.style.opacity = (parseInt(element.style.opacity) || 1) - o;
if(parseInt(element.style.opacity) < o) { // last step
clearInterval(t); // ask the platform to stop calling us
o.style.display = "none"; // mark the element as hidden
}
,16);
}
So basically our code is single threaded - it asks the platform to call it 60 times a second and makes the element a little less visible each time. Everything is always run to completion but except for the first code execution the platform code (the host environment) is calling our code except for vice versa.
So the actual straightforward answer to your question is that the timing of the computation is "taken away" from your code much like in when you make an AJAX request. To answer it directly:
It would not be possible in a single threaded environment without help from outside.
That outside is the enclosing system that uses either threads or operating system asynchronous facilities - our host environment. It could not be done without it in pure standard ECMAScript.
* With the ES2015 inclusion of promises, the language delegates tasks back to the platform (host environment) - but that's an exception.
You have several kind of functions in javascript:
Blocking and non blocking.
Non blocking function will return immediately and the event loop continues execution while it work in background waiting to call the callback function (like Ajax promises).
Animation relies on setInterval and/or setTimeout and these two methods return immediately allowing code to resume. The callback is pushed back into the event loop stack, executed, and the main loop continues.
Hope this'll help.
You can have more information here or here
Event Loop
JavaScript uses what is called an event loop. The event loop is like a while(true) loop.
To simplify it, assume that JavaScript has one gigantic array where it stores all the events. The event loop loops through this event loop, starting from the oldest event to the newest event. That is, JavaScript does something like this:
while (true) {
var event = eventsArray.unshift();
if (event) {
event.process();
}
}
If, during the processing of the event (event.process), a new event is fired (let's call this eventA), the new event is saved in the eventsArray and execution of the current continues. When the current event is done processing, the next event is processed and so on, until we reach eventA.
Coming to your sample code,
$('#mybox').hide(17000);
console.log('Previous command has not yet terminated!');
When the first line is executed, an event listener is created and a timer is started. Say jQuery uses 100ms frames. A timer of 100ms is created, with a callback function. The timer starts running in the background (the implementation of this is internal to the browser), while the control is given back to your script. So, while the timer is running in the background, your script continues to line two. After 100ms, the timer finishes, and fires an event. This event is saved in the eventsArray above, it does not get executed immediately. Once your code is done executing, JavaScript checks the eventsArray and sees that there is one new event, and then executes it.
The event is then run, and your div or whatever element it is moves a few pixels, and a new 100ms timer starts.
Please note that this is a simplification, not the actual working of the whole thing. There are a few complications to the whole thing, like the stack and all. Please see the MDN article here for more info.
Could someone please explain to me the underlying mechanism of the
above? Since .hide() has not yet finished (the animation lasts 17
seconds) and JS engine is dealing with it and it is capable of
executing one command at a time, in which way does it go to the next
line and continues to run the remaining code?
jQuery.fn.hide() internally calls jQuery.fn.animate which calls jQuery.Animation which returns a jQuery deferred.promise() object; see also jQuery.Deferred()
The deferred.promise() method allows an asynchronous function to
prevent other code from interfering with the progress or status of its
internal request.
For description of Promise see Promises/A+ , promises-unwrapping , Basic Javascript promise implementation attempt ; also , What is Node.js?
jQuery.fn.hide:
function (speed, easing, callback) {
return speed == null || typeof speed === "boolean"
? cssFn.apply(this, arguments)
: this.animate(genFx(name, true), speed, easing, callback);
}
jQuery.fn.animate:
function animate(prop, speed, easing, callback) {
var empty = jQuery.isEmptyObject(prop),
optall = jQuery.speed(speed, easing, callback),
doAnimation = function () {
// Operate on a copy of prop so per-property easing won't be lost
var anim = Animation(this, jQuery.extend({},
prop), optall);
// Empty animations, or finishing resolves immediately
if (empty || jQuery._data(this, "finish")) {
anim.stop(true);
}
};
doAnimation.finish = doAnimation;
return empty || optall.queue === false ? this.each(doAnimation) : this.queue(optall.queue, doAnimation);
}
jQuery.Animation:
function Animation(elem, properties, options) {
var result, stopped, index = 0,
length = animationPrefilters.length,
deferred = jQuery.Deferred().always(function () {
// don't match elem in the :animated selector
delete tick.elem;
}),
tick = function () {
if (stopped) {
return false;
}
var currentTime = fxNow || createFxNow(),
remaining = Math.max(0, animation.startTime + animation.duration - currentTime),
// archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497)
temp = remaining / animation.duration || 0,
percent = 1 - temp,
index = 0,
length = animation.tweens.length;
for (; index < length; index++) {
animation.tweens[index].run(percent);
}
deferred.notifyWith(elem, [animation, percent, remaining]);
if (percent < 1 && length) {
return remaining;
} else {
deferred.resolveWith(elem, [animation]);
return false;
}
},
animation = deferred.promise({
elem: elem,
props: jQuery.extend({},
properties),
opts: jQuery.extend(true, {
specialEasing: {}
},
options),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function (prop, end) {
var tween = jQuery.Tween(elem, animation.opts, prop, end, animation.opts.specialEasing[prop] || animation.opts.easing);
animation.tweens.push(tween);
return tween;
},
stop: function (gotoEnd) {
var index = 0,
// if we are going to the end, we want to run all the tweens
// otherwise we skip this part
length = gotoEnd ? animation.tweens.length : 0;
if (stopped) {
return this;
}
stopped = true;
for (; index < length; index++) {
animation.tweens[index].run(1);
}
// resolve when we played the last frame
// otherwise, reject
if (gotoEnd) {
deferred.resolveWith(elem, [animation, gotoEnd]);
} else {
deferred.rejectWith(elem, [animation, gotoEnd]);
}
return this;
}
}),
props = animation.props;
propFilter(props, animation.opts.specialEasing);
for (; index < length; index++) {
result = animationPrefilters[index].call(animation, elem, props, animation.opts);
if (result) {
return result;
}
}
jQuery.map(props, createTween, animation);
if (jQuery.isFunction(animation.opts.start)) {
animation.opts.start.call(elem, animation);
}
jQuery.fx.timer(
jQuery.extend(tick, {
elem: elem,
anim: animation,
queue: animation.opts.queue
}));
// attach callbacks from options
return animation.progress(animation.opts.progress).done(animation.opts.done, animation.opts.complete).fail(animation.opts.fail).always(animation.opts.always);
}
When .hide() is called , a jQuery.Deferred() is created that processes the animation tasks.
This is the reason console.log() is called.
If include start option of .hide() can review that .hide() begins before console.log() is called on next line, though does not block the user interface from performing asynchronous tasks.
$("#mybox").hide({
duration:17000,
start:function() {
console.log("start function of .hide()");
}
});
console.log("Previous command has not yet terminated!");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="mybox">mybox</div>
Native Promise implementation
function init() {
function $(id) {
return document.getElementById(id.slice(1))
}
function hide(duration, start) {
element = this;
var height = parseInt(window.getComputedStyle(element)
.getPropertyValue("height"));
console.log("hide() start, height", height);
var promise = new Promise(function(resolve, reject) {
var fx = height / duration;
var start = null;
function step(timestamp) {
if (!start) start = timestamp;
var progress = timestamp - start;
height = height - fx * 20.5;
element.style.height = height + "px";
console.log(height, progress);
if (progress < duration || height > 0) {
window.requestAnimationFrame(step);
} else {
resolve(element);
}
}
window.requestAnimationFrame(step);
});
return promise.then(function(el) {
console.log("hide() end, height", height);
el.innerHTML = "animation complete";
return el
})
}
hide.call($("#mybox"), 17000);
console.log("Previous command has not yet terminated!");
}
window.addEventListener("load", init)
#mybox {
position: relative;
height:200px;
background: blue;
}
<div id="mybox"></div>

How to write simple asynchronous function in javascript

I want to call a javascript function that takes a long time (5 seconds) to finish without freezing my client's browser. They click the button to start the operation, then they should be notified when it finishes. Currently I have written something like
$(document).ready(function(){
$('#tokenbutton').click(function(){
// IMMEDIATE EFFECT
$('#tokenbutton').attr("disabled",true).val("Computing...");
var callback = function(resultsFromExpensiveOperation){
// CALLBACK EFFECTS
$('#tokenbutton').val("Token computed");
$('#submitbutton').attr("disabled",false);
// ...
};
// FREEZES BROWSER
doExpensiveOperation(callback);
});
});
and
doExpensiveOperation = function(callback){
// ...
//var results = ...
callback(results);
};
but this freezes my browser when I run it. How can I change it so this doesn't freeze my browser?
There are no real asynchronous is javascript, thus no multi thread or anything like that. There is a way to make long running function not freeze the browser in certain cases though.
You can use the setInterval or setTimeout function to do small bits of your long running task at a time, thus each bit takes a fraction of a second and then the ui becomes responsive again for a fraction of a second until the next bit runs. This functionally makes the ui stay responsive and does not add much time (if any) onto the processing of the code. For example.
long running code
function doSomething(){
for(var x = 0; x < 10000; x++){
// do something
}
}
// doing it like this could take forever and lock up the browser
broken up code
var total = 0;
setTimeout(doSomething, 4);
function doSomething(){
for(total = total; total + 100 < 100; total++){
// do something
}
if(total < 10000){
setTimeout(doSomething, 4);
}
}
// doing it like this stops the browser from freezing but does not save any time.
A few things,
I put a time of 4 ms into the setTimout because that is actually the lowest value js will except, even if you put 1 it defaults to 4.
I used a setTimeout pattern instead of a setInterval to prevent the next interval from running before the previous on finishes.
And lastly this pattern does not work for everything. It lends itself best to loop and sequence based operations.
Hope it helps
Use Case
Create a non-Ajax separate process that returns data to a callback.
Solution
Requirements
Browser must:
Support HTML5
Support Web Workers
Structure
Create a separate file for your separate threaded process with the logic. This file must contain the following code:
postMessage( //data )
Code
if(typeof(Worker) === "function") {
var worker = new Worker(//uri to js file);
worker.onmessage = function(event){
// my call back.
};
}

Execution order of multiple setTimeout() functions with same interval

Consider the following Javascript code:
function(){
setTimeout(function() {
$("#output").append(" one ");
}, 1000);
setTimeout(function() {
$("#output").append(" two ");
}, 1000);
}
You can also see this example on jsfiddle.
Can I be sure that the value of #output is always "one two", in that order? Usually, I would handle this problem like this:
function(){
setTimeout(function() {
$("#output").append(" one ");
$("#output").append(" two ");
}, 1000));
}
But I can not do it that way because I get messages from a server which tells me which function to execute (in this example append "one" or append "two"), which I have to execute with a small delay.
I already tested this code in Internet Explorer 9, Firefox 14, Chrome 20 and Opera 12, and the output was always "one two", but can I be sure that this will always be the case?
The Spec is here.
My interpretation of setTimeout step 8 in section 7.3 is that the execution order is supposed to be guaranteed.
However, I investigated this issue because when the window is minimized and then maximised in Chrome, I was finding that timeouts set in events coming from external sources (like websockets or webworkers) were being executed in the wrong order. I assume this is a browser bug and will hopefully be fixed soon.
Play around with this in your fiddle
$(document).ready(function() {
setTimeout(function() {
$("#output").append(" one ");
}, 1000);
});
$(document).ready(function() {
setTimeout(function() {
$("#output").append(" two ");
}, 999);
});​
And you will see that both
output: one two
output: two one
are possible. So Speransky is right that you cannot rely on your timeouts executing in the same order always.
Note that I have change one time with 1ms to show that the timeout 1000ms can execute before the 999ms timeout.
EDIT: The below code can delay execution without any chance of two to be printed before one
function(){
setTimeout(function() {
$("#output").append(" one ");
setTimeout(function() {
$("#output").append(" two ");
}, 100);
}, 1000);
}
Yes, because javascript code is executed in one single thread, all asynchronous events, like click, mousemove, are queued to execute. When you call setTimeout, the engine insert a timer into its queue to execute in future, at least after delay time. So the two setTimeout generate two timers, one after another.
You can have a look at How Javascript Timers Work by John Resig.
No, you cannot be sure. It is asynchronously.
But in fact it probably will be true, because of realization of the mechanism in browsers.
Yes, the output will always be "one two".
Because the first setTimeout always runs before the second setTimeout, if they have same delay time, then the callback function of first will always be executed before the callback function of the second.
Update
I've updated your fiddle with this method. Check it out here
How about this method -- Get a list of things to do from your server --
//Example - append one, append two
var appendList = ['one', 'two']
//then do this
appendList.forEach(function(item, index){
setTimeout(function(){
$('#output').append(item)
}, index * 50 + 1000);
});
This way, you decide the sequence.
If events are synchronous, there is the Continuum function to run functions in sequence:
function keyedSequence(key, fn) {
fn = fn || this;
key.push({fn:fn});
return function() {
for(var i=0, n, full=1; i<key.length; i++) {
n = key[i];
if(n.fn == fn) {
if(!n.called) n.called = 1, n.args = key.slice.call(arguments);
if(!full) break
}
if(!n.called) full = 0
}
if(full) for(i=0; i<key.length; i++)
n = key[i], key[i] = {fn:n.fn}, n.fn.apply(n, n.args);
}
}
Function.prototype.seq = keyedSequence;
You provide an empty array as the key. Functions keyed with the same key will be grouped together.
window.onload = function() {
var key = [];
document.getElementById("test1").addEventListener('click', function1.seq(key), false);
document.getElementById("test2").addEventListener('click', function2.seq(key), false);
}
Click test2, then click test1 and order of execution is still function1 then function2.
Another way of calling it is:
window.onload = function() {
var key = [];
document.getElementById("test1").addEventListener('click', keyedSequence(key, function1), false);
document.getElementById("test2").addEventListener('click', keyedSequence(key, function2), false);
}
It depends on the browser, because setTimout is part of the window object in the browser, not defined in ECMAScript.
Per spec, the have the same task source, and things that have the same task source should be ordered. So yes.

Javascript - how to avoid blocking the browser while doing heavy work?

I have such a function in my JS script:
function heavyWork(){
for (i=0; i<300; i++){
doSomethingHeavy(i);
}
}
Maybe "doSomethingHeavy" is ok by itself, but repeating it 300 times causes the browser window to be stuck for a non-negligible time. In Chrome it's not that big of a problem because only one Tab is effected; but for Firefox its a complete disaster.
Is there any way to tell the browser/JS to "take it easy" and not block everything between calls to doSomethingHeavy?
You could nest your calls inside a setTimeout call:
for(...) {
setTimeout(function(i) {
return function() { doSomethingHeavy(i); }
}(i), 0);
}
This queues up calls to doSomethingHeavy for immediate execution, but other JavaScript operations can be wedged in between them.
A better solution is to actually have the browser spawn a new non-blocking process via Web Workers, but that's HTML5-specific.
EDIT:
Using setTimeout(fn, 0) actually takes much longer than zero milliseconds -- Firefox, for example, enforces a minimum 4-millisecond wait time. A better approach might be to use setZeroTimeout, which prefers postMessage for instantaneous, interrupt-able function invocation, but use setTimeout as a fallback for older browsers.
You can try wrapping each function call in a setTimeout, with a timeout of 0. This will push the calls to the bottom of the stack, and should let the browser rest between each one.
function heavyWork(){
for (i=0; i<300; i++){
setTimeout(function(){
doSomethingHeavy(i);
}, 0);
}
}
EDIT: I just realized this won't work. The i value will be the same for each loop iteration, you need to make a closure.
function heavyWork(){
for (i=0; i<300; i++){
setTimeout((function(x){
return function(){
doSomethingHeavy(x);
};
})(i), 0);
}
}
You need to use Web Workers
https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers
There are a lot of links on web workers if you search around on google
We need to release control to the browser every so often to avoid monopolizing the browser's attention.
One way to release control is to use a setTimeout, which schedules a "callback" to be called at some period of time. For example:
var f1 = function() {
document.body.appendChild(document.createTextNode("Hello"));
setTimeout(f2, 1000);
};
var f2 = function() {
document.body.appendChild(document.createTextNode("World"));
};
Calling f1 here will add the word hello to your document, schedule a pending computation, and then release control to the browser. Eventually, f2 will be called.
Note that it's not enough to sprinkle setTimeout indiscriminately throughout your program as if it were magic pixie dust: you really need to encapsulate the rest of the computation in the callback. Typically, the setTimeout will be the last thing in a function, with the rest of the computation stuffed into the callback.
For your particular case, the code needs to be transformed carefully to something like this:
var heavyWork = function(i, onSuccess) {
if (i < 300) {
var restOfComputation = function() {
return heavyWork(i+1, onSuccess);
}
return doSomethingHeavy(i, restOfComputation);
} else {
onSuccess();
}
};
var restOfComputation = function(i, callback) {
// ... do some work, followed by:
setTimeout(callback, 0);
};
which will release control to the browser on every restOfComputation.
As another concrete example of this, see: How can I queue a series of sound HTML5 <audio> sound clips to play in sequence?
Advanced JavaScript programmers need to know how to do this program transformation or else they hit the problems that you're encountering. You'll find that if you use this technique, you'll have to write your programs in a peculiar style, where each function that can release control takes in a callback function. The technical term for this style is "continuation passing style" or "asynchronous style".
You can make many things:
optimize the loops - if the heavy works has something to do with DOM access see this answer
if the function is working with some kind of raw data use typed arrays MSDN MDN
the method with setTimeout() is called eteration. Very usefull.
the function seems to be very straight forward typicall for non-functional programming languages. JavaScript gains advantage of callbacks SO question.
one new feature is web workers MDN MSDN wikipedia.
the last thing ( maybe ) is to combine all the methods - with the traditional way the function is using only one thread. If you can use the web workers, you can divide the work between several. This should minimize the time needed to finish the task.
I see two ways:
a) You are allowed to use Html5 feature. Then you may consider to use a worker thread.
b) You split this task and queue a message which just do one call at once and iterating as long there is something to do.
There was a person that wrote a specific backgroundtask javascript library to do such heavy work.. you might check it out at this question here:
Execute Background Task In Javascript
Haven't used that for myself, just used the also mentioned thread usage.
function doSomethingHeavy(param){
if (param && param%100==0)
alert(param);
}
(function heavyWork(){
for (var i=0; i<=300; i++){
window.setTimeout(
(function(i){ return function(){doSomethingHeavy(i)}; })(i)
,0);
}
}())
There is a feature called requestIdleCallback (pretty recently adopted by most larger platforms) where you can run a function that will only execute when no other function takes up the event loop, which means for less important heavy work you can execute it safely without ever impacting the main thread (given that the task takes less than 16ms, which is one frame. Otherwise work has to be batched)
I wrote a function to execute a list of actions without impacting main thread. You can also pass a shouldCancel callback to cancel the workflow at any time. It will fallback to setTimeout:
export const idleWork = async (
actions: (() => void)[],
shouldCancel: () => boolean
): Promise<boolean> => {
const actionsCopied = [...actions];
const isRequestIdleCallbackAvailable = "requestIdleCallback" in window;
const promise = new Promise<boolean>((resolve) => {
if (isRequestIdleCallbackAvailable) {
const doWork: IdleRequestCallback = (deadline) => {
while (deadline.timeRemaining() > 0 && actionsCopied.length > 0) {
actionsCopied.shift()?.();
}
if (shouldCancel()) {
resolve(false);
}
if (actionsCopied.length > 0) {
window.requestIdleCallback(doWork, { timeout: 150 });
} else {
resolve(true);
}
};
window.requestIdleCallback(doWork, { timeout: 200 });
} else {
const doWork = () => {
actionsCopied.shift()?.();
if (shouldCancel()) {
resolve(false);
}
if (actionsCopied.length !== 0) {
setTimeout(doWork);
} else {
resolve(true);
}
};
setTimeout(doWork);
}
});
const isSuccessful = await promise;
return isSuccessful;
};
The above will execute a list of functions. The list can be extremely long and expensive, but as long as every individual task is under 16ms it will not impact main thread. Warning because not all browsers supports this yet, but webkit does

Categories

Resources