Display image and run script for fifteen seconds

This is very similar to the question I asked the other day, but my page code has become much more complex, and I need to revise it. I used the following code:

$('#myLink').click(function() {
  $('#myImg').attr('src', 'newImg.jpg');
  setTimeout(function() { $('#myImg').attr('src', 'oldImg.jpg'); }, 15000);
});

To replace the image with a predetermined period of time (15 seconds) when you click the link, then after 15 seconds, return the original image.

However, now I would like to run a javascript snippet, also when I click on the link (in addition to replacing the image) and only when I click on the link (this is due to the 15 second image), and then my js code also disappears after 15 seconds ... however, I’m not sure how to send js code to the page in jquery ... Basically I just want jQuery to “echo” this code on page under second 15 while I'm there, but I don’t know how jquery formats it " 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 (); This is a webcam script. It basically takes a new image every half second and replaces it on the page. You have to forgive me, I'm new to jquery, I don't know how to make this script work in the jquery context.

Sorry, I’m not explaining well. This is what I need, step by step:

  • , : " , -"
  • -, 0,5 script .
  • 15 - , " , -"

15- - script, , . .

+3
1

... ( , , , ( , ))

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
});
+2

Source: https://habr.com/ru/post/1747782/


All Articles