I've been having trouble finding any delays right after a function is executed. The problem is that the href loads a little slow and the function takes in effect before the _target page is loaded. You can see the change coming into effect immediately. I'd like to have a little timer to wait a few seconds before the function takes affect.
I've tried setInterval inside a var, but it doesn't seem to be working. setInterval by itself keeps running once the page is clicked and I don't want that. I want the timer to be started once the image is clicked and the link loaded.
<script type='text/javascript'>
function change() {
var image = document.getElementById('doge');
image.src = 'img/doge.png';
document.getElementById("text").innerHTML="<b>such wow</b> much amaze <b><i>very effort</b></i>"
}
</script>
<img src='Logo_256.png' alt='doge' id='doge' onclick='change();'>
<small id='text'>This page was last modified on Wednesday, November 20, 2013 8:43:13 PM</small>
I assure you everything works, so don't mind if the .jpg or .png match up (just edited right now).
Add a timeout to the things that the function does, so the delay occurs when the function runs what you want to happen in your change() function after a setTimeout():
var change = function(){
setTimeout(function() {
var image = document.getElementById('doge');
image.src = 'img/doge.png';
document.getElementById("text").innerHTML="<b>such wow</b> much amaze <b><i>very effort</b></i>"
}, 5000);
};
Related
I'm trying to play a sound every time a user gets a new notification. The way I am loading the notifications on my page is simple:
(function($)
{
$(document).ready(function()
{
var $container = $("#noti");
$container.load("notify.php");
var refreshId = setInterval(function()
{
$container.load('notify.php');
}, 1000);
});
})(jQuery);
This works by updating a div container with whatever number the PHP code sends out. it retries every second (probably not the most efficient way, but it works).
I have another piece of code that checks when the div content changes, then creates an alert box (which I will change to playing a sound when the script is done):
var myElement = document.getElementById('noti');
if(window.addEventListener) {
// Normal browsers
myElement.addEventListener('DOMSubtreeModified', contentChanged, false);
} else
if(window.attachEvent) {
// IE
myElement.attachEvent('DOMSubtreeModified', contentChanged);
}
function contentChanged() {
// this function will run each time the content of the DIV changes
alert("js is working");
}
This script works, however it also creates an alert or the first loading of the notifications. This is because it starts of as an empty div, then it loads the data, which sets off this alert script. The only way I could think about going round this is delaying the script from loading for a couple of seconds whilst the AJAX script does its business.
Does anyone know a way I could delay this second script from doing anything for the first few seconds after page load, or perhaps a better way about going round this?
Instead of doing that, use a custom event which you trigger when load finishes:
var refreshId = setInterval(reloadContainer, 1000)
function reloadContainer() {
$container.load('notify.php', function success() {
$container.trigger('loaded')
})
}
$(myElement).on('loaded', contentChanged)
This question already has an answer here:
JavaScript Image onload event binding
(1 answer)
Closed 8 years ago.
I am displaying some thumbnails which periodically get regenerated by an external process on the server. I want to display a spinner (gif) on the ones that are currently missing when the page loads, and replace the spinners with their thumbnails when they eventually arrive. Displaying a spinner is trivial. The thumbnail filenames are all known in advance. I haven't been able to figure out a way to watch for them to show up in Javascript.
It can be many minutes until some of the thumbnails get created. The process that creates them deletes them just before it does new processing which results in a new thumbnail. The interval between these external processing episodes can be hours.
Can anyone think of a way to do this? (no Ajax or Jquery - just basic Javascript).
Thanks.
EDIT - I'm sure this could be improved but it seems to work. Thanks for the hints and suggestions. It gave me the idea I was looking for. Someone with the ability to do so might want to remove the note at the top about this question already being answered with the link - that question is not relevant. --JKC
var intervalId, thumbs;
function refresh_thumbs() {
// Refresh whether they need it or not. If the thumb isn't there,
// onerror will (re)load the spinner.
for (i=0; i<thumbs.length; i++) {
id = "snap_"+i;
document.getElementById(id).src = thumbs[i];
}
}
function init(thumbstring) {
// Split comma-separated string into an array of thumbnail links
thumbs=thumbstring.split(",");
refresh_thumbs();
intervalId = window.setInterval( refresh_thumbs, 5000); // milliseconds
}
As an example, one page might be generated containing the following:
<img src='/d/thumb_0.png' id='snap_0' onerror='this.src="/s/spinner.gif";'>
<img src='/d/thumb_1.png' id='snap_1' onerror='this.src="/s/spinner.gif";'>
<script>
init("/d/thumb_0.png,/d/thumb_1.png");
</script>
Calling refresh_thumbs before setInterval is necessary to prevent having to wait 5 seconds to see the thumbs which are there to begin with.
I have a suspicion I don't need the intervalId saved for any reason.
Use setInterval to periodically change the src of the images that are waiting. You can append a query string to the image URL in the form of a timestamp to prevent caching. Not sure how you detect if an image is ready or not this way, but I'm sure that's easy to figure out with some trial and error.
Update: onerror triggers for each unreachable URL you set. Keep polling URLs with new timestamps until you stop receiving errors (that means the image is ready).
Update: I played around with this problem trying to find a general solution. Here's what I came up with:
HTML:
<body style="background-color: #CCC;">
<img src="/img/fail.png" width=200 onerror="imgErr(this);" />
<img src="/img/fail.png" width=200 onerror="imgErr(this);" />
<img src="/img/fail.png" width=200 onerror="imgErr(this);" />
<img src="/img/fail.png" width=200 onerror="imgErr(this);" />
<img src="/img/fail.png" width=200 onerror="imgErr(this);" />
<img src="/img/fail.png" width=200 onerror="imgErr(this);" />
</body>
JS:
var imgElems = [],
imgUrls = [];
function imgErr(img) {
imgElems.push(img);
//imgUrls.push(img.src); // <-- real code
imgUrls.push('/img/logo.png'); // <-- literal url for testing
}
onload = function () {
var interval,
timeout = 3000,
time,
url,
img;
interval = setInterval(function () {
time = new Date().getTime();
while (imgElems.length) {
img = imgElems.shift();
url = imgUrls.shift();
img.src = url + '?time=' + time;
}
}, timeout);
}
JSFiddle
If I'm understanding correctly, your issue isn't knowing when the image loads; your issue is that you can't issue a request for the image because it may take hours to load. So when you set the src, it times out, and that's all the information you get.
You have a few choices.
Perhaps the easiest way to get the file is continuously attempt to reload each image. In that case, you're close, though you'll want a separate div with the spinner to show while waiting:
<img src='spinner.gif' id='spinner' />
<img src='thumb.png' id='thumb' />
document.getElementById("thumb").onload = function() {
document.getElementById("spinner").style[display] = "hidden";
}
document.getElementById("thumb").onerror = function() {
this.src = "thumb.png";
}
You'd need to tweak the positioning, but this will make a spinner, make it disappear when the image loads, and attempt to reload it when the image is not yet ready.
The other alternative I was going to suggest has already been suggested by Jo Are By - set an interval every few minutes to reset the source of the images. There are lots of variations you can do here (reset all sources, or only failed ones, e.g.), but basically, at the end of your file, you'll want something like this:
var intervalId = window.setInterval( function() {
var elem = document.getElementById("thumb");
// set the source twice, since I dont' see anywhere in the spec if setting
// the src to itself forces a reload.
var src = elem.src;
elem.src = "http://foofoofoofoofoo.bar.bar";
elem.src = src;
}, 300000); // set to every 5 minutes (300 seconds * 1000 milliseconds)
Somewhere in there, you'll need to keep track of how many are still pending, and when it hits 0, call window.clearInterval(intervalId);.
I have made a carousel and using JavaScript setInterval() function for rotate image with fixed interval in carousel. Here's the script that I had used:
var timeOut = 4000;
function showSlide() {
//....script for showing image
}
function pauseSlide() {
setInterval(function(){showSlide();}, timeOut);
}
jQuery(document).ready(function() {
pauseSlide();
});
Now the problem is when I have change the browser tab and after few minute back again to carousel browser and what I seen carousel running too faster rather than default time interval, images going to change fast suppose 0 time interval. Please help me with how I can sort this out.
You must get rid of the first interval before starting another, or you start getting more than one interval working simultaneously (i.e. why you start seeing it go "faster")
Do this
var timeOut = 4000;
var interval = 0;
function showSlide() {
//....script for showing image
}
function pauseSlide() {
clearInterval(interval);
interval = setInterval(function(){showSlide();}, timeOut);
}
jQuery(document).ready(function() {
//NOW you can do multiple pauseSlide() calls
pauseSlide();
pauseSlide();
pauseSlide();
pauseSlide();
pauseSlide();
});
From what I know in newer versions of both firefox and chrome, background tabs have setTimeout and setInterval clamped to 1000ms to improve performance. So I think that your issue might relate to that.
Maybe this will help : How can I make setInterval also work when a tab is inactive in Chrome?
Image changing faster than expected may indicate that you have more than one call to pauseSlide(), in one way or another.
Is document ready the only place you call the function ? Any code in showslide or anywhere triggering a document ready event ? If you put an alert() in pauseSlide(), does it popup more than once ?
My website works in a way so that any links clicked do not load a new page but however trigger a .load() event into a div named "content".
Everything has been nice and dandy but now I have run into a small problem.
On one of the content pages, I have the following code:
$('.count').each(function () {
$this = $(this);
countdown = setInterval(function(){
countnow = parseInt($('.remain', $this).html());
$('.remain', $this).html(countnow-1);
}, 1000);
return false;
});
The code works... it works very well. But when I load that same page again, it seems like the code is running twice because the seconds are going down by 2 at a time. Then when I load it again, it's going down by 3 seconds at a time. Another load, and it goes down by 4 seconds at a time. I load it a couple more times and it goes down faster then I can read.
I tried giving the .count divs their own unique id's (the .remain div is nested inside the .count div), even when pages are subsequently loaded the id is still entirely different and this did not fix my problem. I also tried putting clearInterval(countdown) right before the function but that just made it stop working entirely. Any suggestions?
And yes I know the countdown doesn't currently stop when it reaches 0.
Try this:
var countdown;
$('.count').each(function () {
$this = $(this);
if (!countdown)
countdown = setInterval(function(){
countnow = parseInt($('.remain', $this).html());
$('.remain', $this).html(countnow-1);
}, 1000);
return false;
});
I have a Javascript which is a little larger so I tried to show a .gif on the begin off the script and hide it after its finished. But if i do so the script runs and does all steps in one process so the picture is never shown. How can I force javascript to complete the show of the picture before run the rest of the script?
Apart from the fact that it's not a good idea to have long-running javascript code, you could show the image and start the javascript using window.setInterval():
showBusy();
window.setTimeout(function() { startLongCode(); }, 100);
This will show the busy indicator and start your function 100ms later.
You have to work with the Load event Jquery img.load question
-- EDIT
var myImg = new Image();
myImg.src = "my.jpg";
var myFunction = function(){
//code...
}
myImg.onLoad = function() {
myFunction();
}
Obj Img
You should extend this example to your need. I hope it will be useful.