0

I have an html page and I'm using JavaScript to create a function that display 2 images (the first between second 5 and second 10 and the second image between second 10 and second 20) and repeat that every 30 seconds. I tried

var cmp=0
function main() {
window.setTimeout(main,30000);
cmp+1;
if (cmp >= 5 and cmp < 10)
    show_image_1 ();
if (cmp >= 10 and cmp < 15)
    show_image_2 ();
}

but I didn't find out how to check the time every second.

3
  • 1
    Add complete code. See minimal reproducible example Commented Nov 17, 2015 at 10:47
  • If you want to check the time every second, you need your script to run once a second. Also, mind that setTimeout() expects a parameter in milliseconds, not seconds. Commented Nov 17, 2015 at 10:50
  • 1
    setInterval would suit you better. Commented Nov 17, 2015 at 10:51

2 Answers 2

1

Define an Interval, and then display the image based on that:

window.setInterval(updateImg, 1000);
var timer = 0;
var imageSrc = document.getElementById("imageSrc");
imageSrc.style.display = "none";

function updateImg() {
    timer += 1;
    if (timer > 30) {
        timer = 0;
    }
    if (timer >= 5 && timer <= 10) {
        imageSrc.style.display = "block";
        imageSrc.src = "http://lorempicsum.com/futurama/255/200/1";
    } else if (timer >= 10 && timer <= 20) {
        imageSrc.style.display = "block";
        imageSrc.src = "http://lorempicsum.com/futurama/255/200/2";
    } else {
        imageSrc.style.display = "none";
    }
}
<img src="" id="imageSrc">

JsFiddle: http://jsfiddle.net/ghorg12110/z6vfn1nb/

Sign up to request clarification or add additional context in comments.

2 Comments

it worked very well but how can I make it stop when timer = 30
Just remove if (timer > 30) { timer = 0; }
0

Here is my proposal:

// Define the images and the duration of each one in seconds (a missing "src" means the image will be empty):
var steps=[
    {duration: 2},
    {duration: 3, src:'one.jpg'},
    {duration: 5, src:'two.jpg'},
    {duration: 5},
];

// Index of current step: Will cylce from 0 to steps.length:
var currentStep=0;

// Periodic function to show the current step, and re-invokes itself cyclically:
function nextStep()
{
    var step=steps[currentStep];
    var img=document.getElementById("myimg");
    if (step.src)
    {
        img.src=step.src;
        img.style.visibility="visible";
    }
    else
    {
        // When there is no "src" in the current step: Hide the image:
        img.style.visibility="hidden";
    }
    currentStep=(++currentStep % steps.length);
    setTimeout(nextStep, 1000*step.duration);
}

To start the cycle, you have to call nextStep().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.