Skip to content

Instantly share code, notes, and snippets.

@johanbove
Created June 2, 2015 12:25
Show Gist options
  • Save johanbove/584d396431eb67cb4e4f to your computer and use it in GitHub Desktop.
Save johanbove/584d396431eb67cb4e4f to your computer and use it in GitHub Desktop.
Unblocking the browser while long processes run using setTimeout or requestAnimationFrame
var hasRequestAnimationFrame = (window.requestAnimationFrame) ? true : false,
updateProgress = function (percent) {
$progress.text((percent < 100) ? percent.toFixed(2) + "%" : 100 + "%");
},
// @see http://stackoverflow.com/questions/672732/prevent-long-running-javascript-from-locking-up-browser
doCalculation = function () {
//do your thing for a short time
self.addNoteToDetails(news[i]);
i -= 1;
//figure out how complete you are
var percent_complete = 100 - i / len * 100;
return percent_complete;
},
pumpWithAnimationFrame = function () {
var percent_complete = doCalculation();
//maybe update a progress meter here!
updateProgress(percent_complete);
//carry on pumping?
if (percent_complete < 100) {
window.requestAnimationFrame(pumpWithAnimationFrame);
}
},
pumpWithSetTimeout = function () {
var percent_complete = doCalculation();
//maybe update a progress meter here!
updateProgress(percent_complete);
//carry on pumping?
if (percent_complete < 100) {
setTimeout(pumpWithSetTimeout, throttle);
}
};
this.$newsDetails = $("#newsDetails").html('');
$progress = $("<div/>", { "class": "progress" }).text("0%");
$(".details_title h1").append($progress);
//console.info("Creating %d items", len);
//start the calculation
if (hasRequestAnimationFrame) {
pumpWithAnimationFrame();
} else {
pumpWithSetTimeout();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment