Fares Omrani
Fares Omrani

Reputation: 255

Javascript check counter and repeat function

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.

Upvotes: 0

Views: 295

Answers (2)

Little Santi
Little Santi

Reputation: 8793

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().

Upvotes: 0

Magicprog.fr
Magicprog.fr

Reputation: 4100

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/

Upvotes: 1

Related Questions