Reputation: 6906
This is very similar to a question I asked the other day but my page code has become significantly more complicated and I need to revisit it. I've been using the following code:
$('#myLink').click(function() {
$('#myImg').attr('src', 'newImg.jpg');
setTimeout(function() { $('#myImg').attr('src', 'oldImg.jpg'); }, 15000);
});
To replace an image for a set period of time (15 seconds) when the link is clicked, then after 15 seconds, revert to the original image.
However now, I'd like to run a snippet of javascript as well when the link is clicked (in addition to replacing the image), and only when the link is clicked (it's related to the 15 second image) and then have the js code disappear as well after the 15 seconds...however I'm not sure how to have jquery send js code into the page...Basically I just want jQuery to "echo" this code onto the page underneath the 15 second while I am there, but I don't know how jquery formats this "echo".
Does this question make sense?
interval = 500;
imgsrc = "webcam/image.jpg";
function Refresh() {
tmp = new Date();
tmp = "?" + tmp.getTime();
document.images["image1"].src = imgsrc + tmp;
setTimeout("Refresh()", interval);
}
Refresh(); It's script for a webcam. Basically it takes a new picture every half a second and replaces it on the page. You must forgive me, I'm new to jquery, I don't know how to make this script work in a jquery context.
i'm sorry, I'm explaining badly. This is what I need to happen, step by step:
It is ONLY during that 15 second interval that I wan the webcam refresh script running, otherwise it's wasting bandwidth on an element that isn't even shown. Sorry for the confusion.
Upvotes: 3
Views: 816
Reputation: 844
this should do the trick for you... (though you probably could try detecting if they have left the page (I can't give you any suggestions on how to do that))
var myLink = $('#myLink');
var myImg = $('#myImg');
myLink.click(function() {
// makes sure this can only run once per 15sec
myLink.attr('disabled', 'disabled');
var start = new Date();
var interval = null;
function refresh() {
var current = new Date();
if (current.getTime() - start.getTime() > 15000) { // max time in miliseconds
//stops refresh
clearInterval(interval);
// lets them click on the link again
myLink.attr('disabled', '');
// resets the old img
myImg.attr('src', 'oldImg.jpg');
} else {
// should be obvious
myImg.attr('src', 'webcam/image.jpg?t=' + current.getTime());
}
}
// refreshes page
interval = setInterval(refresh, 500);
refresh(); // don't wait for the first 1/2 second
});
Upvotes: 2