Callback after all animates done - javascript

Code
I need help making callback after all animate methods inside do_animations are done. For one animate i could call promise and done function. I tried using $.Callbacs but i don't know how to make promise object from fire method.
function random_num(a, b) {
return Math.floor(Math.random() * (b - a + 1)) + a;
}
function do_animations() {
var n = random_num(1, 5);
for (var i = 0; i < n; i++) {
var width = random_num(-50, 50);
$('#rec').animate({'left': '+=' + width + 'px'}, 300);
}
}
$(document).ready(function(){
do_animations();
});
Best solution would be
do_animations().done(function(){ ... });

Using promise():
DEMO
function do_animations() {
var n = random_num(1, 5),
$rec = $('#rec');
for (var i = 0; i < n; i++) {
var width = random_num(-50, 50);
$rec.animate({'left': '+=' + width + 'px'}, 300);
}
return $rec.promise();
}
$(document).ready(function(){
do_animations().done(function(){ alert("All animations done!") });
});

Related

DIV animation and property change

I'm trying to simulate TCP packet transmission and sliding window, and fortunately I've made much progress. But now I want to fix a minor issue with the sliding window, which is a sliding DIV:
Hopefully if you are familiar with TCP's slow start, the window size double up to a number, and then increments by one. This is working. Now what I want to fix is sliding to right. So I want to automatically slide one step right when each ack is received at the original machine. Currently it does not move when the ack is received; so each time I press the button, it retransmits many of the previous packets! My work is here: http://web.engr.illinois.edu/~shossen2/CS438/Project/
$(document).ready(function () {
var count = 0;
var items = 0;
var packetNumber = 0;
var speed = 0;
var ssth= $("#ssth").val();
var window_left=0;
for (var i = 1; i <= 32; i++) {
$('#table').append("<div class='inline' id='"+i+"'>"+i+"</div>");
}
document.getElementById(1).style.width = 22;
$("button").click(function() {
if (items < ssth) {
if (items == 0)
items = 1;
else
items = items * 2;
count++;
} else {
items = items + 1;
}
window_left += 20;
window_width=items * 20;
document.getElementById("window_size").innerHTML = items;
document.getElementById("window").style.left= window_left + "px";
document.getElementById("window").style.width=window_width + "px";
speed = +$("#speed").val();
createDivs(items);
animateDivs();
});
function createDivs(divs) {
packetNumber = 1;
var left = 60;
for (var i = 0; i < divs; i++) {
var div = $("<div class='t'></div>");
div.appendTo(".packets");
$("<font class='span'>" + (parseInt(packetNumber) + parseInt(window_left/20) -1) + "</font>").appendTo(div);
packetNumber++;
div.css({
left: left
/* opacity: 0*/
}).fadeOut(0);
//div.hide();
//left += 20;
}
}
function animateDivs() {
$(".t").each(function (index) { // added the index parameter
var packet = $(this);
packet
.delay(index * 200)
.fadeIn(200, function() {
$('#table #' + (index + window_left/20)).css({background:'yellow'});
})
.animate({left: '+=230px'}, speed)
.animate({left: '+=230px'}, speed)
.fadeOut(200, function () {
packet
.css({
top: '+=20px',
backgroundColor: "#f09090"
})
.text('a' + packet.text());
})
.delay(500)
.fadeIn(200)
.animate({left:'-=230px'}, speed)
.animate({left:'-=230px'}, speed)
.fadeOut(200, function () {
packet
.css({
top: '-=20px',
backgroundColor: "#90f090"
});
$('#table #' + (index + window_left/20)).css({background:'lightgreen'});
});
}).promise().done(function(){
$(".packets").empty();
});
}
});

Central JS Timer

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

Looking for thoughts on improvement of my javascript (jquery) code. Recursive function

I have made this code that makes some visual "tiles" that fades in and out.
But at the moment I'm having a little performance problem.
Though most browers are running the code okay (especially firefox), some like safari have problems after a while (a while = like 15 seconds).
I think its due to my recursive function (the function named changeopacity that calls itself forever on a delay)? or is it?
But anyways the problem is that this code is really heavy for most browsers. Is there, or more how can I make this code perform any better? any thoughts? (code examples would be nice) thanks :-)
The actual code:
$(document).ready(function () {
var aniduration = 2000;
var tilesize = 40;
createtable(tilesize);
$(".tile").each(function (index, domEle) {
var randomdelay = Math.floor(Math.random() * 3000);
setTimeout(function () {
changeopacity(aniduration, domEle);
}, randomdelay);
});
$("td").click(function () {
clickanimation(this, 9);
});
$("td").mouseenter(function () {
var element = $(this).find("div");
$(element).clearQueue().stop();
$(element).animate({opacity: "0.6"}, 800);
});
$("td").css("width", tilesize + "px").css("height", tilesize + "px");
});
function createtable(tilesize) {
var winwidth = $(window).width();
var winheight = $(window).height();
var horztiles = winwidth / tilesize;
var verttiles = winheight / tilesize;
for (var y = 0; y < verttiles; y++)
{
var id = "y" + y;
$("#tbl").append("<tr id='" + id + "'></tr>");
for (var x = 0; x < horztiles; x++)
{
$("#" + id).append("<td><div class='tile' style='opacity: 0; width: " + tilesize + "px; height: " + tilesize + "px;'></div></td>");
}
}
}
function changeopacity(duration, element){
var randomnum = Math.floor(Math.random() * 13);
var randomopacity = Math.floor(Math.random() * 7);
var randomdelay = Math.floor(Math.random() * 1000);
if ($(element).css("opacity") < 0.3)
{
if (randomnum != 4)
{
if ($(element).css("opacity") != 0)
animation(element, 0, duration, randomdelay);
}
else
{
animation(element, randomopacity, duration, randomdelay);
}
}
else
{
animation(element, randomopacity, duration, randomdelay);
}
setTimeout(function () {
return changeopacity(duration, element);
}, duration + randomdelay);
}
function animation(element, randomopacity, duration, randomdelay){
$(element).clearQueue().stop().delay(randomdelay).animate({opacity: "0." + randomopacity}, duration);
}
function clickanimation(column, opacitylevel) {
var element = $(column).find("div");
$(element).clearQueue().stop();
$(element).animate({"background-color": "white"}, 200);
$(element).animate({opacity: "0." + opacitylevel}, 200);
$(element).delay(200).animate({opacity: "0.0"}, 500);
//$(element).delay(600).animate({"background-color": "black"}, 500);
}
The number one issue is that you are creating one setTimeout for every single cell on your page. The only browser capable of handling that is Internet Explorer, and then it fails due to the many CSS changes causing slow redraws.
I would strongly suggest programming your own event scheduler. Something like this, which I used in a university project:
var timer = {
length: 0,
stack: {},
timer: null,
id: 0,
add: function(f,d) {
timer.id++;
timer.stack[timer.id] = {f: f, d: d, r: 0};
timer.length++;
if( timer.timer == null) timer.timer = setInterval(timer.run,50);
return timer.id;
},
addInterval: function(f,d) {
timer.id++;
timer.stack[timer.id] = {f: f, d: d, r: d};
timer.length++;
if( timer.timer == null) timer.timer = setInterval(timer.run,50);
return timer.id;
},
remove: function(id) {
if( id && timer.stack[id]) {
delete timer.stack[id];
timer.length--;
if( timer.length == 0) {
clearInterval(timer.timer);
timer.timer = null;
}
}
},
run: function() {
var x;
for( x in timer.stack) {
if( !timer.stack.hasOwnProperty(x)) continue;
timer.stack[x].d -= 50;
if( timer.stack[x].d <= 0) {
timer.stack[x].f();
if( timer.stack[x]) {
if( timer.stack[x].r == 0)
timer.remove(x);
else
timer.stack[x].d = timer.stack[x].r;
}
}
}
}
};
Then, instead of using setTimeout, call timer.add with the same arguments. Similarly, instead of setInterval you can call timer.addInterval.
This will allow you to have as many timers as you like, and they will all run off a single setInterval, causing much less issues for the browser.
Nice animation :-) However, I found some bugs and possible improvements:
Your table is not rebuilt on window resizes. Not sure if bug or feature :-)
Use delegated events. You have a lot of elements, and every event handler is costly. Sadly, this won't work for the non-bubbling mouseenter event.
It would be nice if you would not use inline styles for with and height - those don't change. For the divs, they are superflouos anyway.
I can't see a reason for all those elements to have ids. The html-string building might be more concise.
Cache the elements!!! You are using the jQuery constructor on nearly every variable, building a new instance. Just reuse them!
Your changeopacity function looks a bit odd. If the opacity is lower than 0.3, there is 1-in-13-chance to animate to zero? That might be expressed more stringent. You also might cache the opacity to a variable instead of reading it from the dom each time.
There is no reason to pass the duration and other constants as arguments, they do never change and can be used from the global scope.
Instead of using the timeout, you should use the complete callback of the animate method. Timeouts are never accurate, they may even interfere here causing (minor) problems.
var duration = 2000,
tilesize = 40,
clickopacity = 0.9;
$(document).ready(function () {
filltable($("#tbl"), tilesize)
.on("click", "td", clickanimation);
$(".tile").each(function() {
changeopacity($(this));
});
$("#tbl div").mouseenter(function () {
$(this).clearQueue()
.stop()
.animate({opacity: "0.6"}, 800);
});
});
function filltable(tbl, tilesize) {
var win = $(window).width();
var horztiles = win.width() / tilesize;
var verttiles = win.height() / tilesize;
for (var y = 0; y < verttiles; y++) {
var tr = "<tr>";
for (var x = 0; x < horztiles; x++)
tr += "<td style='width:"+tilesize+"px;height:"+tilesize+"px;'><div class='tile' style='opacity:0;'></div></td>");
tbl.append(tr+"</tr>");
}
return tbl;
}
function changeopacity(element) {
var random = Math.floor(Math.random() * 13);
var opacity = Math.floor(Math.random() * 7);
var delay = Math.floor(Math.random() * 1000);
if (element.css("opacity") < 0.3 && random != 4)
opacity = 0;
element.clearQueue().stop().delay(delay).animate({
opacity: "0." + opacity
}, duration, function() {
changeopacity(element);
});
}
function clickanimation() {
$(this.firstChild)
.clearQueue()
.stop()
.animate({"background-color": "white"}, 200)
.animate({opacity: "0." + clickopacity}, 200)
.delay(200).animate({opacity: "0.0"}, 500);
//.delay(600)
//.animate({"background-color": "black"}, 500);
}

jQuery How to Have Variable Increment by Value in a Recursive Function

I have a JS Function which is called in document.ready. The intent is as it scrolls to the bottom window, it'll load more from the JSON API.
The API has the parameter offset and limit. Offset controls which subset of results you are seeing. For ex. 20-40 would be offset=20 and limit controls how many you can view at once.
I thought I would approach this with a recursive function which calls itself each time the user goes to the bottom of the window, with window.scroll. Once they go to the bottom, it'll increment the offset by 20 each time, then run the function again.
Problem: I can't seem to get it to increment the variable by 20 to make this work. Thoughts?
function getData(offset) {
var jsonCallback = "&jsoncallback=?";
//var offset = 20;
//var offset += 20;
var limit = 20;
var characterURL = "http://api.example.com/character&byId=" + characterID + "&offset=" + offset + "&limit=" + limit;
$.getJSON(characterURL + jsonCallback, function(data) {
for (i=0; i < (data.data.results).length; i++) {
var $characterUl = $("<ul>");
$characterUl.appendTo("#characterComics");
$("<li>").text(data.data.results[i].title).appendTo($characterUl);
$("<li>").text(data.data.results[i].id).appendTo($characterUl);
$("<li>").text(data.data.results[i].release_date).appendTo($characterUl);
if (data.data.results[i].release_date > 0) {
$characterLi.text(data.data.results[i].issue_number).appendTo($characterUl);
}
}
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() > $(document).height() - 10) {
while ((data.data.results).length === offset || (data.data.results).length > offset) {
offset = offset+20;
$("<div>").text(offset).appendTo("body");
getComics(offset);
}
}
});
});
}
$(document).ready(function() {
var $characterComics = $("<div>", {id : "characterComics"});
$characterComics.appendTo("body");
getData(0);
});
UPDATED
Read this more as a pseudo-code
function getData(offset) {
var jsonCallback = "&jsoncallback=?",
characterURL = "http://api.example.com/character&byId=" + characterID + "&offset=" + offset + "&limit=" + limit;
$.getJSON(characterURL + jsonCallback, function(data) {
for (i=0; i < (data.data.results).length; i++) {
var $listItem = $("<li>");
listItem.append("<span>"+data.data.results[i].title+"</span>");
listItem.append("<span>"+data.data.results[i].id+"</span>");
listItem.append("<span>"+data.data.results[i].release_date+"</span>");
if (data.data.results[i].release_date > 0) {
listItem.append("<span>"+data.data.results[i].issue_number+"</span>");
}
listItem.appendTo($characterUl);
itemsLoaded++;
}
});
}
$(document).ready(function() {
var $characterComics = $("<div>", {id : "characterComics"}),
$characterUl = $("<ul>"),
offset = 0,
itemsLoaded = 0;
limit = 20;
$characterComics.appendTo("body");
$characterUl.appendTo($characterComics);
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() > $(document).height() - 10) {
if ("check here if you reached your offsets") {
offset = offset+20;
getData(offset);
}
}
});
// get your first set of data
getData(0);
});

i want a delay of 100millisec while running each loop

for(i=100;i>=0;i--){
icon.style.filter="alpha(opacity=0)";
}
this is my for loop ... wat i want is tat each time for loop completes 1 loop it should wait or sleep for 100millisec so tat it can give a fadding effect....
You should call setTimeout, which will execute a function after a given delay.
For example:
function fadeOut(i) {
i = i || 100;
icon.style.filter = "alpha(opacity=" + i + ")";
icon.style.opacity = i / 100;
i--;
if (i > 0)
setTimeout(function() { fadeOut(i) }, 100); //Call fadeOut in 100 milliseconds
}
You can also call setInterval, which will keep calling the function until you call clearInterval.
For example:
function fadeOut() {
var i = 100;
var timer = setInterval(function() {
icon.style.filter = "alpha(opacity=" + i + ")";
icon.style.opacity = i / 100;
i--;
if (i <= 0)
clearInterval(timer);
}, 100);
}
You can do this much more easily using the jQuery library, like this:
$(icon).fadeOut();
John Resig wrote very cool JavaScript functions for fading in and out (Editing slightly):
function fadeOut(elem, time)
{
var t = time / 100;
var c = 0;
for (var b = 100; b >= 0; b -= 5)
{
c +=5;
(function(){
var pos = b;
setTimeout(function(){
setOpacity(elem, pos);
}, ((c + 1) * t));
})();
}
}
function fadeOut(elem, time)
{
show(elem);
var t = time / 100;
var c = 0;
for (var b = 100; b >= 0; b -= 5)
{
c +=5;
(function(){
var pos = b;
setTimeout(function(){
setOpacity(elem, pos);
}, ((c + 1) * t));
})();
}
}
function show(elem)
{
elem.style.display = '';
}
function setOpacity(elem, level)
{
if (elem.filters)
{
elem.style.filters = 'alpha(opacity=' + level + ')';
}
else
{
elem.style.opacity = level / 100;
}
}
You would then use it like:
var el = document.getElementById("#element");
fadeIn(el,1000); //Fade in over 1 second
fadeOut(el,1000); //Fade out over 1 second
EDIT:
Would be easier with jQuery, but you would learn how it works using normal JavaScript
$("#element").fadeOut();
$("#element").fadeIn();

Categories