I have a long running script that broke down in a progress bar:
HTML
<div id="progressbar-wrapper">
<div id="progressbar-outer" style="display: table;margin: 0 auto;background-color: #FFFFFF;border: 5px solid #000000;width: 50%;height: 30px;opacity: 1;z-index: 9998">
<div id="progressbar" style="float:left;width: 0;height: 30px;background-color:#000000;border: 0;opacity: 1;z-index: 99999">
</div>
</div>
<div id="loading-animation" style="position: fixed;top: 150px;left: 0;height: 120px;width: 100%;font-size: 100px;line-height: 120px;text-align: center;color: #000000;z-index: 9999;">
...SAVING...<br /><small>Saving Lines</small>
</div>
</div>
JavaScript
var uiprogressbar = {};
$(function () {
uiprogressbar = {
/** initial progress */
progress: 0,
/** maximum width of progressbar */
progress_max: 0,
/** The inner element of the progressbar (filled box). */
$progress_bar: $('#progressbar'),
/** Method to set the progressbar.
*/
set: function (num) {
if (this.progress_max && num) {
this.progress = num / this.progress_max * 100;
console.log('percent: ' + this.progress + '% - ' + num + '/' + this.progress_max);
this.$progress_bar.width(String(this.progress) + '%');
}
},
fn_wrap: function (num) {
setTimeout(function () {
this.set(num);
}, 0);
}
};
});
//PROGRESS BAR ================================================
//max progress bar
uiprogressbar.progress_max = iterations;
var mainGrid = $("#mainGrid").data("kendoGrid");
var i = 0; //partition #
var j = 0; //line #
var linesUpdated = 0; //update complete #
//make the progress bar visable before updating
$("#progressbar-wrapper").css("display", "block");
//then loop through update grid methods
(function innerloop() {
try {
//If end
var testPart = (partitions[i].length - 1); //30 but starts at 0
} catch (err) {
//exit loop
return;
}
//Get the length of the partition
var thisPartitionLength = (partitions[i].length - 1); //30 but starts at 0
if (thisPartitionLength >= j && successComplete === 2) {
$.each(mainGrid.dataSource.data(),
function () {
if (this.RowSelected === true) {
//get id
var row = mainGrid.dataSource.getByUid(this.uid);
//unselect and turn off dirty
row.set("RowSelected", "false");
row.set("dirty", "false");
linesUpdated++;
}
});
//update line #
j++;
//update progressbar
uiprogressbar.set(linesUpdated);
}
if (j <= thisPartitionLength) {
//loop if not complete with partition
setTimeout(innerloop, 0);
} else {
if (j > thisPartitionLength) {
//if end of partition reset the line # and increase partition # and continue loop
i++;
j = 0;
setTimeout(innerloop, 0);
}
//on complete
if (linesUpdated === iterations) {
//Success message
alert("Saved");
}
}
})();
Which works perfectly in chrome. But doesn't appear AT ALL in IE11 (which is what my clients use). When i run it in IE it even gives and error
...not responding due to a long-running script.
which was the exact reason i implemented a progress bar. Is there something I'm missing that IE has that Chrome does not? How can i change this to make it work in IE?
OK so IE waits till the function is complete to make changes. I has to strip out the progress bar method into a separate function and wrap it in a timeout:
function updateProgressBar(){
//PROGRESS BAR ================================================
//max progress bar
uiprogressbar.progress_max = iterations;
var mainGrid = $("#mainGrid").data("kendoGrid");
var i = 0; //partition #
var j = 0; //line #
var linesUpdated = 0; //update complete #
//make the progress bar visable before updating
$("#progressbar-wrapper").css("display", "block");
//then loop through update grid methods
(function innerloop() {
try {
//If end
var testPart = (partitions[i].length - 1); //30 but starts at 0
} catch (err) {
//exit loop
return;
}
//Get the length of the partition
var thisPartitionLength = (partitions[i].length - 1); //30 but starts at 0
if (thisPartitionLength >= j && successComplete === 2) {
$.each(mainGrid.dataSource.data(),
function () {
if (this.RowSelected === true) {
//get id
var row = mainGrid.dataSource.getByUid(this.uid);
//unselect and turn off dirty
row.set("RowSelected", "false");
row.set("dirty", "false");
linesUpdated++;
}
});
//update line #
j++;
//update progressbar
uiprogressbar.set(linesUpdated);
}
if (j <= thisPartitionLength) {
//loop if not complete with partition
setTimeout(innerloop, 0);
} else {
if (j > thisPartitionLength) {
//if end of partition reset the line # and increase partition # and continue loop
i++;
j = 0;
setTimeout(innerloop, 0);
}
//on complete
if (linesUpdated === iterations) {
//Success message
alert("Saved");
}
}
})();
}
then call it using:
setTimeout(function() {
updateProgressBar();
}, 0);
Related
I got function within JS which is supposed to show random order divs on btn click.
However once the btn is clicked user got to wait for initial 10 seconds ( which is set by: setInterval(showQuotes, 10000) ) for divs to start showing in random order which is not ideal for me.
JS:
var todo = null;
var div_number;
var used_numbers;
function showrandomdivsevery10seconds() {
div_number = 1;
used_numbers = new Array();
if (todo == null) {
todo = setInterval(showQuotes, 10000);
$('#stop-showing-divs').css("display", "block");
}
}
function showQuotes() {
used_numbers.splice(0, used_numbers.length);
$('.container').hide();
for (var inc = 0; inc < div_number; inc++) {
var random = get_random_number();
$('.container:eq(' + random + ')').show();
}
$('.container').delay(9500).fadeOut(2000);
}
function get_random_number() {
var number = randomFromTo(0, 100);
if ($.inArray(number, used_numbers) != -1) {
return get_random_number();
} else {
used_numbers.push(number);
return number;
}
}
function randomFromTo(from, to) {
return Math.floor(Math.random() * (to - from + 1) + from);
}
Question: How to alter the code so upon the btn click divs will start showing right away without initial waiting for 10 seconds? (take in mind I want to keep any further delay of 10 seconds in between of each div being shown)
Thank you.
Call it when you begin the interval
todo = setInterval((showQuotes(),showQuotes), 10000);
I want to run simulations and update a progress bar, but the progress bar gets updated in a "jumpy" way. Eg. it moves from 21% to 34% to 76%. I'd like to to move one-by-one from 21% to 22% to 23% etc.
Consider this as a SSCCE:
http://embed.plnkr.co/XIKxpV6oWyWiwklFBSLh/
HTML
<button>Simulate</button>
JS
$(document).ready(function () {
var $button = $('button');
var worker = new Worker("worker.js");
worker.addEventListener("message", function(e) {
if (e.data) {
switch (e.data.cmd) {
case "progress":
$button.text((e.data.value / 250).toFixed(0) + "%");
break;
case "complete":
$button.text("Simulate");
break;
}
}
});
$button.on("click", function() {
worker.postMessage("start");
});
});
Worker
this.addEventListener("message", function(e) {
if (e.data === "start") {
for (var n = 0; n < 250000000; ++n) {
if (n % 10000 === 1) {
this.postMessage({cmd: "progress", value: n / 10000});
}
}
this.postMessage({cmd: "complete"});
}
});
How can I get it to update smoothly? Why isn't it updating smoothly to begin with?
You could change progress to provide fill values.
The reason why it's not smooth is that it doesn't post a progress value for all values, only every 10000 (if you try to post every value it's very likely your browser is going to freeze)
if (n % 10000 === 1) {
this.postMessage({cmd: "progress", value: n / 10000});
}
So you don't get all possible % values, you need to fill.
Something like this
$(document).ready(function () {
var $button = $('button');
var last = 0
var worker = new Worker("worker.js");
worker.addEventListener("message", function process(e) {
if (e.data) {
switch (e.data.cmd) {
case "progress":
var next = (e.data.value / 250)
var current = last
// fill values
// from last % to new %
for (; current < next; ++current) {
$button.text(current + "%")
}
last = current
$button.text(next.toFixed(0) + "%");
break;
case "complete":
$button.text("Simulate");
break;
}
}
});
$button.on("click", function() {
worker.postMessage("start");
});
});
The code is meant to animated some text in a typing fashion. I want it to run once, but it keeps looping through the area of sentences. How would i go about stopping it looping through. The top of the code gathers the value of a input and puts into the array, this all works fine. It is just the looping i am having issues with.
var yourWord = document.getElementById("myText").value;
var yourtext = "I took the word " + yourWord + "...";
var infomation = [yourtext,
'I looked at the most relevant news article relating to it...',
'And created this piece of art from the words in the article! '
],
part,
i = 0,
offset = 0,
pollyLen = Polly.length,
forwards = true,
skip_count = 0,
skip_delay = 5,
speed = 100;
var wordflick = function () {
setInterval(function () {
if (forwards) {
if (offset >= infomation[i].length) {
++skip_count;
if (skip_count == skip_delay) {
forwards = false;
skip_count = 0;
}
}
} else {
if (offset == 0) {
forwards = true;
i++;
offset = 0;
if (i >= pollyLen) {
i = 0;
}
}
}
part = infomation[i].substr(0, offset);
if (skip_count == 0) {
if (forwards) {
offset++;
} else {
offset--;
}
}
$('#pollyInfo').text(part);
}, speed);
};
$(document).ready(function () {
wordflick();
});
Modify the line:
setInterval(function () {
into:
var interval = setInterval(function () {
and then clear the interval where you are setting i=0;
if (i >= pollyLen) {
i = 0;
}
to:
if (i >= pollyLen) {
i = 0;
clearInterval(interval);
}
This should do the job!
Looking at Secrets of the JavaScript Ninja, I took this code for a "Central Timer":
var timers = {
timerID: 0,
timers: [],
add: function(fn) {
this.timers.push(fn);
},
start: function() {
if(this.timerID) return;
(function runNext() {
if(timers.timers.length > 0) {
for (var i = 0; i < timers.length; i++) {
if(timers.timers[i]() === false) {
timers.timers.splice(i,1);
i--;
}
}
console.log("setting timeout.");
timers.timerID = setTimeout(runNext, 0);
}
})();
},
stop: function() {
clearTimeout(this.timerID);
this.timerID = 0;
}
};
Then, test it out.
var box = document.getElementById("box"), x = 0, y = 20;
timers.add(function() {
box.style.left = x + "px";
log.console("x:", x);
if(++x > 50) return false;
});
timers.add(function() {
box.style.top = y + "px";
y += 2;
log.console("y:", y);
if (++y > 120) return false;
});
console.log("starting timer.");
But, looking at my console, I see setting timeout scrolling endlessly without any increment to x or y.
What's going on here?
JsFiddle
EDIT Page # - 210/394.
Note - it's possible I made a copy/paste mistake - not blaming.
timers.length is undefined in the for loop in runNext, so the code does not actually iterate over the intended array. Either you transcribed it incorrectly or the code in the book has a bug. Regardless, this is the correct loop:
// ↓↓↓↓↓↓↓
for (var i = 0; i < timers.timers.length; i++) {
if(timers.timers[i]() === false) {
timers.timers.splice(i,1);
i--;
}
}
Fiddle
I'm using this javascript and the slide show slides right to left with the images in this order and positon:
start postion > 1 | 2 | 3 | 4 | 5 | 6 etc etc
but I want to swap them so they run in this position
6 | 5 | 4 | 3 | 2 | 1 < start position
Kind of like reading a book back to front, but keeping it in the right order
I've been told I need to modify the lines labelled below: //MODIFY ME
I hope someone can help! Thank you
Here's my code
(function($) {
$.fn.slideshow = function(method) {
if ( this[0][method] ) {
return this[0][ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return this.each(function() {
var ANIMATION_DURATION = .6; // The duration to flick the content. In seconds.
var MOVE_THRESHOLD = 10; // Since touch points can move slightly when initiating a click this is the
// amount to move before allowing the element to dispatch a click event.
var itemWidth;
var horizontalGap;
var $this = $(this);
var collection;
var viewItems = [];
var touchStartTransformX; // The start transformX when the user taps.
var touchStartX; // The start x coord when the user taps.
var interval; // Interval used for measuring the drag speed.
var wasContentDragged; // Flag for whether or not the content was dragged. Takes into account MOVE_THRESHOLD.
var targetTransformX; // The target transform X when a user flicks the content.
var touchDragCoords = []; // Used to keep track of the touch coordinates when dragging to measure speed.
var touchstartTarget; // The element which triggered the touchstart.
var selectedIndex = 0; // The current visible page.
var viewPortWidth; // The width of the div that holds the horizontal content.
var isAnimating;
var pageChangedLeft;
// The x coord when the items are reset.
var resetX;
var delayTimeout;
init(method);
function init(options) {
collection = options.data;
renderer = options.renderer;
itemWidth = options.itemWidth;
horizontalGap = options.horizontalGap;
initLayout();
$this[0].addEventListener("touchstart", touchstartHandler);
$this[0].addEventListener("mousedown", touchstartHandler);
viewPortWidth = $this.width();
$this.on("webkitTransitionEnd", transitionEndHandler);
collection.on("add", addItem);
}
// MODIFY ME
function initLayout() {
// Layout five items. The one in the middle is always the selected one.
for (var i = 0; i < 5; i++) {
var viewItem;
if (i > 1 && collection.at(i - 2)) // Start at the one in the middle. Subtract 2 so data index starts at 0.
viewItem = new renderer({model: collection.at(i - 2)});
else
viewItem = new renderer();
viewItem.render().$el.appendTo($this);
viewItem.$el.css("left", itemWidth * i + horizontalGap * i);
viewItem.setState(i != 2 ? "off" : "on");
viewItems.push(viewItem);
}
// Center the first viewItem
resetX = itemWidth * 2 - ($this.width() - itemWidth - horizontalGap * 4) / 2;
setTransformX(-resetX);
}
function getCssLeft($el) {
var left = $el.css("left");
return Number(left.split("px")[0]);
}
// MODIFY ME
function transitionEndHandler() {
if (pageChangedLeft != undefined) {
var viewItem;
if (pageChangedLeft) {
// Move the first item to the end.
viewItem = viewItems.shift();
viewItems.push(viewItem);
viewItem.model = collection.at(selectedIndex + 2);
viewItem.$el.css("left", getCssLeft(viewItems[3].$el) + itemWidth + horizontalGap);
} else {
// Move the last item to the beginning.
viewItem = viewItems.pop();
viewItems.splice(0, 0, viewItem);
viewItem.model = collection.at(selectedIndex - 2);
viewItem.$el.css("left", getCssLeft(viewItems[1].$el) - itemWidth - horizontalGap);
}
viewItem.render();
// Reset the layout of the items.
for (var i = 0; i < 5; i++) {
var viewItem = viewItems[i];
viewItem.$el.css("left", itemWidth * i + horizontalGap * i);
viewItem.setState(i != 2 ? "off" : "on");
}
// Reset the transformX so we don't run into any rendering limits. Can't find a definitive answer for what the limits are.
$this.css("-webkit-transition", "none");
setTransformX(-resetX);
pageChangedLeft = undefined;
}
}
function touchstartHandler(e) {
clearInterval(interval);
wasContentDragged = false;
transitionEndHandler();
// Prevent the default so the window doesn't scroll and links don't open immediately.
e.preventDefault();
// Get a reference to the element which triggered the touchstart.
touchstartTarget = e.target;
// Check for device. If not then testing on desktop.
touchStartX = window.Touch ? e.touches[0].clientX : e.clientX;
// Get the current transformX before the transition is removed.
touchStartTransformX = getTransformX();
// Set the transformX before the animation is stopped otherwise the animation will go to the end coord
// instead of stopping at its current location which is where the drag should begin from.
setTransformX(touchStartTransformX);
// Remove the transition so the content doesn't tween to the spot being dragged. This also moves the animation to the end.
$this.css("-webkit-transition", "none");
// Create an interval to monitor how fast the user is dragging.
interval = setInterval(measureDragSpeed, 20);
document.addEventListener("touchmove", touchmoveHandler);
document.addEventListener("touchend", touchendHandler);
document.addEventListener("mousemove", touchmoveHandler);
document.addEventListener("mouseup", touchendHandler);
}
function measureDragSpeed() {
touchDragCoords.push(getTransformX());
}
function touchmoveHandler(e) {
var deltaX = (window.Touch ? e.touches[0].clientX : e.clientX) - touchStartX;
if (wasContentDragged || Math.abs(deltaX) > MOVE_THRESHOLD) { // Keep track of whether or not the user dragged.
wasContentDragged = true;
setTransformX(touchStartTransformX + deltaX);
}
}
function touchendHandler(e) {
document.removeEventListener("touchmove", touchmoveHandler);
document.removeEventListener("touchend", touchendHandler);
document.removeEventListener("mousemove", touchmoveHandler);
document.removeEventListener("mouseup", touchendHandler);
clearInterval(interval);
e.preventDefault();
if (wasContentDragged) { // User dragged more than MOVE_THRESHOLD so transition the content.
var previousX = getTransformX();
var bSwitchPages;
// Compare the last 5 coordinates
for (var i = touchDragCoords.length - 1; i > Math.max(touchDragCoords.length - 5, 0); i--) {
if (touchDragCoords[i] != previousX) {
bSwitchPages = true;
break;
}
}
// User dragged more than halfway across the screen.
if (!bSwitchPages && Math.abs(touchStartTransformX - getTransformX()) > (viewPortWidth / 2))
bSwitchPages = true;
if (bSwitchPages) {
if (previousX > touchStartTransformX) { // User dragged to the right. go to previous page.
if (selectedIndex > 0) { // Make sure user is not on the first page otherwise stay on the same page.
selectedIndex--;
tweenTo(touchStartTransformX + itemWidth + horizontalGap);
pageChangedLeft = false;
} else {
tweenTo(touchStartTransformX);
pageChangedLeft = undefined;
}
} else { // User dragged to the left. go to next page.
if (selectedIndex + 1 < collection.length) {// Make sure user is not on the last page otherwise stay on the same page.
selectedIndex++;
tweenTo(touchStartTransformX - itemWidth - horizontalGap);
pageChangedLeft = true;
} else {
tweenTo(touchStartTransformX);
pageChangedLeft = undefined;
}
}
} else {
tweenTo(touchStartTransformX);
pageChangedLeft = undefined;
}
} else { // User dragged less than MOVE_THRESHOLD trigger a click event.
var event = document.createEvent("MouseEvents");
event.initEvent("click", true, true);
touchstartTarget.dispatchEvent(event);
}
}
// Returns the x of the transform matrix.
function getTransformX() {
var transformArray = $this.css("-webkit-transform").split(","); // matrix(1, 0, 0, 1, 0, 0)
var transformElement = $.trim(transformArray[4]); // remove the leading whitespace.
return transformX = Number(transformElement); // Remove the ).
}
// Sets the x of the transform matrix.
function setTransformX(value) {
$this.css("-webkit-transform", "translateX("+ Math.round(value) + "px)");
}
function tweenTo(value) {
isAnimating = true;
targetTransformX = value;
// Set the style for the transition.
$this.css("-webkit-transition", "-webkit-transform " + ANIMATION_DURATION + "s");
// Need to set the timing function each time -webkit-transition is set.
// The transition is set to ease-out.
$this.css("-webkit-transition-timing-function", "cubic-bezier(0, 0, 0, 1)");
setTransformX(targetTransformX);
}
// MODIFY ME
function addItem(folio) {
clearTimeout(delayTimeout);
// Create a timeout in case multiple items are added in the same frame.
// When the timeout completes all of the view items will have their model
// updated. The renderer should check to make sure the model is different
// before making any changes.
delayTimeout = setTimeout(function(folio) {
var index = collection.models.indexOf(folio);
var dataIndex = index;
var firstIndex = selectedIndex - 2;
var dataIndex = firstIndex;
var viewItem;
for (var i = 0; i < viewItems.length; i++) {
viewItem = viewItems[i];
if (dataIndex >= 0 && dataIndex < collection.length) {
viewItem.model = collection.at(dataIndex);
viewItem.render();
}
viewItem.setState(i != 2 ? "off" : "on");
dataIndex += 1;
}
}, 200);
}
// Called when the data source has changed. Resets the view with the new data source.
this.setData = function(data) {
$this.empty();
viewItems = [];
collection = data;
selectedIndex = 0;
initLayout();
}
});
} else {
$.error( 'Method ' + method + ' does not exist on Slideshow' );
}
}
})(jQuery);
From what I can make out, you need to simply "flip" the loops that create the sides in the slideshow so that it makes the last slide where it was making the first. It seems to do this in two places.
Then, you will need to amend the code which adds a slide to make it add it before the other slides instead of after.
This sounds an awful lot like homework - it's always best to attempt an answer before asking on here. An example on a site like JSFiddle is also generally appreciated.