jQuery text() does not work before a setTimeout? - javascript

After an Ajax request, I perform the following.
$('#change_ts').text('Defaults Changed!');
//blinking part
var t = setTimeout($('#change_ts').fadeIn('slow'), 500);
clearTimeout(t);
var t = setTimeout($('#change_ts').fadeOut('slow'), 500);
clearTimeout(t);
var t = setTimeout($('#change_ts').fadeIn('slow'), 500);
clearTimeout(t);
var t = setTimeout($('#change_ts').fadeOut('slow'), 500);
clearTimeout(t);
var t = setTimeout($('#change_ts').fadeIn('slow'), 500);
clearTimeout(t);
var t = setTimeout($('#change_ts').fadeOut('slow'), 500);
clearTimeout(t);
var t = setTimeout($('#change_ts').fadeIn('slow'), 500);
clearTimeout(t);
var t = setTimeout($('#change_ts').text('Change Text/Size'), 500);
clearTimeout(t);
It is my make-shift fade in/out blinker. It works well.
However, the first line has no effect when I perform the blinking part. If I remove the blinking the text of the span is changed. But as soon as I uncomment the blinker, it doesn't change the text at all?!
Any ideas why this is?
Thanks all for any help
Update
The set timeout is useless for what I need to do. I have removed it now and I have the following, but I still can not change the text before the fade in/outs?
$('#change_ts').text('Defaults Changed!');
$('#change_ts').fadeIn('slow');
$('#change_ts').fadeOut('slow');
$('#change_ts').fadeIn('slow');
$('#change_ts').fadeOut('slow');
$('#change_ts').fadeIn('slow');
$('#change_ts').fadeOut('slow');
$('#change_ts').fadeIn('slow');
$('#change_ts').text('Change Text/Size');

How about using the jQuery Blink plugin instead. You can see the demo here :)

You should pass a callback function to setTimeout, like this:
var t = setTimeout(function() { $('#change_ts').fadeIn('slow') }, 500);
Right now, you're calling the fade function immediately and sending the return value to setTimeout. You should also change the timeout values to be increasing, like 500, 1000, 1500 etc., otherwise all the fade in/out will occur at the same time. You could use a loop to set-up the values for you. And why are you clearing the timers immediately - they won't have any effect if you do so.
for (var i = 1; i <= 6; i += 2) {
setTimeout(function() { $('#change_ts').fadeIn('slow') }, 500 * i);
setTimeout(function() { $('#change_ts').fadeOut('slow') }, 500 * (i + 1));
}
You can also make a generic blinker like this, which will keep blinking until you clear the timer:
var state = true;
function blink() {
state = !state;
if (state)
$('#change_ts').fadeIn('slow');
else
$('#change_ts').fadeOut('slow');
}
var t = setInterval(blink, 500);
This will keep going until you call clearInterval(t).
Update: The reason the first text call has no effect is because the second text call is executed immediately and the text is overwritten. Note that the fadeIn and fadeOut return immediately, before the animation is completed, so the second text call executes right after that. If you want to wait until the animation is complete, you need to attach a callback to the last fade function, like this:
$('#change_ts').fadeIn('slow', function() {
$('#change_ts').text('Change Text/Size');
});

Related

Blinking text in a button

I have this function to blink text in a button "AddMoney" :-
function blinker1(){
document.getElementById("AddMoney").value="Add Money";
setTimeout("document.getElementById('AddMoney').value=' '", 500);
xxxx = setTimeout("blinker1()",1500);
}
And I stop it and set the text with this function:-
function cease1() {
clearTimeout(xxxx);
document.getElementById("AddMoney").value="Add Money";
}
It works but now and again there is no text in the button.
Anyone Know why and how to fix.
Now and again there is no text in the button. Anyone Know why?
It happens whenever cease1() is called while setTimeout("document.getElementById('AddMoney').value=' '",500) is still scheduled, which happens on average every third time. In that case, the blinker1() timeout is cancelled and the content is shown, but shortly after it will be hidden again.
… and how to fix?
You'll have to cancel both timeouts:
var timerA, timerB;
function blinker() {
document.getElementById("AddMoney").value = "Add Money";
timerA = setTimeout(function() {
document.getElementById('AddMoney').value = "";
}, 500);
timerB = setTimeout(blinker1, 1500);
}
function cease1() {
clearTimeout(timerA);
clearTimeout(timerB);
document.getElementById("AddMoney").value = "Add Money";
}
Alternatively, use two functions that are mutually scheduling each other so that only one timer is active at a time:
var timer;
function blinkerA() {
document.getElementById("AddMoney").value = "Add Money";
timer = setTimeout(blinkerB, 500);
}
function blinkerB() {
document.getElementById('AddMoney').value = "";
timer = setTimeout(blinkerA, 1000);
}
function cease1() {
clearTimeout(timer);
document.getElementById("AddMoney").value = "Add Money";
}
This version should work a bit better for you. I stuck with vanilla Javascript rather the introducing jQuery:
Fiddle
var blink = window.setInterval(blinker1, 900)
function blinker1() {
var addMoney = document.getElementById("addMoney");
addMoney.innerHTML = " ";
setTimeout(function(){addMoney.innerHTML = "ADD MONEY"}, 300);
}
document.getElementById('stop').addEventListener('click', function(){
clearInterval(blink);
})
Note - it would be better and easier to achieve a blink effect using pure CSS.
The text disappears because you only set clearTimeout on xxxx, so the timeout for setTimeout("document.getElementById('AddMoney').value=' '", 500); will always execute. I think this is the reason why there is no text in the button.
My approach would be to set a counter, let say the text need to blink 10 times (based on your code it will take 15sec.) Each time when the text shown the counter will decrease until it reaches 0.
sample code (https://jsfiddle.net/2trodftu/1/)
//counter
var blinkCounter = 10;
// blink method
function blink() {
document.getElementById("AddMoney").value="Add Money";
if (blinkCounter > 0) {
setTimeout("document.getElementById('AddMoney').value=' '", 500);
setTimeout(blink,1500);
}
blinkCounter = blinkCounter - 1;
}
//initializer
blink();
Hope this helps.

Issues with resetting an interval

I have two elements. When I click the left element I want to change the right element into another element. If the left element is not clicked again the right element changes back to its original state. I've been able to make that happen, but I want to be able to click on that element again and have the interval I set restart. I feel like I'm close.
var changeImage = function(){
if(imageClicked == true){
var Img = document.getElementById('Img');
Img.setAttribute('src', "./images/img2.jpg");
imageTimeout = setTimeout(function(){
var Image = document.getElementById('Image');
Image.setAttribute('src', './images/image.jpg');
}, 3000)
imageClicked = false;
return imageTimeout;
} else {
imageClicked = true;
resetTimer();
}
}
var resetTimer = function(){
clearTimeout(imageTimeout);
window.setTimeout(imageTimeout, 3000);
}
random_image.addEventListener("click", changeImage, false);
The problem is that you are calling setTimeout(function ,delay) without a callback function.
The issue is in this line in the else block:
window.setTimeout(imageTimeout, 3000);
where imageTimeout is not a function, but the id of the timeout.
You need to create a separate function (let's call it timeoutFunction for example) with the timeout code and call it every time you invoke setTimeout.
After you create that function, and call it in the if block as well, change that line to:
imageTimeout = window.setTimeout(timeoutFunction, 3000);
from your code:
function timeoutFunction(){
var flowerImage = document.getElementById('flowerP');
flowerImage.setAttribute('src', './images/flowers.jpg');
}
by the way, you can define that flowerImage variable outside that function once instead of searching the DOM every time.
In order to clear a timeout, you need to call the clearTimeout function with the reference to the object that was returned by window.setTimeout. So you need to change your code to:
var resetTimer = function() {
clearTimeout(timeoutId);
createjs.Sound.stop(playSoundD);
timeoutId = window.setTimeout(imagetimeout, 3000);
console.log("I've been reset");
}

Execute after cleartimeout function finished (jQuery)

I have this istuation. I have a setTimeout to a function in which I fade out and fade in an element. In a few seconds this timeout is cleared with cleartimeout and right after is called .hide() to hide this element. The problem is that sometimes it doesnt hide the element. I have a feeling it has something to do with timing.
Example:
function first_func(){
$('.element').fadeOut(function(){
// Do other stuff like change element's position
$('.element').fadeIn();
});
interval1 = setTimeout(function(){first_func()},500);
}
function second_func(){
countdown--;
if (countdown<0){
last_func();
}
interval2 = setTimeout(function(){second_func()},1000);
}
function begin_func(){
first_func();
second_func();
}
function last_func(){
clearTimeout(interval1);
clearTimeout(interval2);
$('.element').hide();
}
So basically the problem is that in last_func I clear both intervals and HIDE the element, but sometimes the element is still visible on the page. So I am guessing that it does hide but the interval is still in progress and it fades back in.
If anyone would have some suggestion please
Just a suggestion, but this bit appears wrong to me:
function second_func(){
countdown--;
if (countdown<0){
end_func();
}
interval2 = setTimeout(function(){second_func()},1000);
}
Even if you're calling end_func() to stop everything, you're setting a new timeout after that.
function second_func(){
countdown--;
if (countdown<0){
end_func();
} else {
interval2 = setTimeout(second_func, 1000);
}
}
Another hint: To avoid that running fadeIn/fadeOuts affect the hiding of the element, you should clear the animation queue:
$('.element').stop(true, true).hide();
By default fadeIn and fadeOut use duration of 400 milliseconds, u can change it by set first parameter.
$('.element').fadeOut( [duration] [, callback] );
You seem to never call last_func, is end_func() supposed to be last_func()?
This works:
http://jsfiddle.net/CZ9hr/1/
May I suggest a simpler approach for what you seem to want to achieve: http://jsfiddle.net/fSEjR/2/
var countdown = 3,
$element = $('.element');
for (var i = 0; i < countdown; i++) {
$element.fadeOut().fadeIn(function() {
countdown--;
if (countdown === 0) $element.hide();
});
};
This works because animations are automatically queued in jquery.

infinte loop while trying to display buffer symbol as pics preload

I am really getting frustrated with this. So I am making a slideshow with javascript but while all the images are being loaded I would like to show a buffering symbol..
here is the buffering symbol code.. if you have a better way of doing it please speak up.
function loadAnimation(){
setTimeout(
"document.getElementById('main_photo_img').src = 'images/loadBar1.jpg'", 300);
setTimeout(
"document.getElementById('main_photo_img').src = 'images/loadBar2.jpg'", 600);
setTimeout(
"document.getElementById('main_photo_img').src = 'images/loadBar3.jpg';", 900);
}
that displays 3 images that make up a buffer animation.
my code for playing it until an image is loaded is this..
while(!pic1.onload){
loadAnimation();
}
All that happens though is an infinite loop.
Try something like this:
function loadAnimation() {
var i = 0,
timer;
(function k() {
var cur = i++ % 3 + 1;
document.getElementById('main_photo_img').src = 'images/loadBar' + cur + '.jpg';
timer = setTimeout(k, 300);
})()
return {
cancel: function () {
clearTimeout(timer);
}
};
}
....
var animation = loadAnimation();
pic1.onload = animation.cancel; //The cancel will be called when pic1 loads. You may add other code in the cancel function if needed
I'd probably just use a gif or css background sprites, setting src dynamically is probably the hackiest way to do this I've seen to date ;p
Here's a recursive setTimeout version which I think is what you're looking for.
var i = 0, intervalId;
function animate(){
var newImg = 'images/loadBar' + ((i++ % 3) + 1) + '.jpg'
document.getElementById('main_photo_img').src = newImg;
intervalId = setTimeout(animate, 300);
}
And again, you'd stop this with
clearInterval(intervalId);
To start it with the first image showing up immediately you'd simply call
animate();
But to have the first image wait 300ms before showing, you would do
intervalId = setTimeout(animate, 300);

Stopping increment at specific height

I am animating images within a logo in a slot-machine type of animation. I need it to stop animating once it gets to the top of the image (and send a callback if possible).
Currently, this is how I'm accomplishing the animation:
window.setInterval(function() {
$('#title-1 img').animate({bottom : '-=60px'})
}, 5000);
Any ideas on how I would get it to stop, and to send the callback?
So I assume you have a sprite image containing multiple logos, you want them to slide each 5 seconds until you reach the last one, and then call the callback?
var cnt = 6,
$img = $('#title-1 img'),
i = 0;
function animate_logo(cb) {
if (i < cnt) {
$('#title-1 img').animate({bottom : '-=60px'});
i += 1;
setTimeout(function () {animate_logo(cb)}, 5000);
}
else {
cb();
}
}();
var interval = window.setInterval(function() {
$('#title-1 img').animate({bottom : '-=60px'},
function(){
if(`some stop point`) clearInterval(interval);
}
);
}, 5000);
I would not suggest using a setInterval when dealing with animations due to the way newer browsers are making changes to the way setInterval and setTimeout work when the tab is not the active tab.
var $title1 = $("#title-1");
var $title1img = $title1.find('img');
function anim(){
if ($title1.height() < parseInt($title1img.css("bottom"))) {
setTimeout(function(){
$title1img.animate({bottom : '-=60px'},anim);
},5000);
}
}
$title1img.animate({bottom : '-=60px'},anim);
Edit: another reason not to use setInterval to fire off animations is due to the reqeustAnimationFrame that was implemented in 1.6 and removed in 1.6.3, which will more than likely be added back in 1.7. If you write code now that will be compatible later, that's less maintenance you will have to do later if you end up being required to upgrade.
Here's a jsfiddle http://jsfiddle.net/czUnU/
Edit: function...
function animColumn(title,img){
function anim(){
if (title.height() < parseInt(img.css("bottom")) {
setTimeout(function(){
img.animate({bottom : '-=60px'},anim);
},5000);
}
}
img.animate({bottom : '-=60px'},anim);
}
animColumn($("#title-1"),$("#title-1 img"));
animColumn($("#title-2"),$("#title-2 img"));
animColumn($("#title-3"),$("#title-3 img"));
http://jsfiddle.net/czUnU/1/

Categories

Resources