Eldar Blrs
Eldar Blrs

Reputation: 43

JQuery blinking image in cycle

I have the blinking image. There is a jquery code:

function blink(){
        $("#light_3_1").animate({"opacity": 0}, 400 ).animate({"opacity": 1}, 400 );
    }   
    $(document).ready(function(){
        setInterval(blink, 500);
    });

I want to make delay effect(10 seconds of blinking, then stop for some time, then again blinking and again stop...), but i can't find the way how to do it.

Upvotes: 2

Views: 861

Answers (2)

Leo Javier
Leo Javier

Reputation: 1403

Since you want to stop after 10segs(10,000 ms) you just need to increment a variable to turn off the SetInterval.

Here I made a sample for you: http://jsfiddle.net/leojavier/t83tb683/

However you should use CSS animation that way your animations are not going to impact your javascript thread.

$(document).ready(function(){
     var counter = 0;

    function blink(){
       $("#light_3_1").animate({"opacity": 0}, 400 ).animate({"opacity": 1}, 400 );
        counter++;
        if(counter > 9) {
            clearInterval(interval);
        }
    }   
     var interval = setInterval(blink, 500);
});

Here is a version with CSS (RECOMMENDED): http://jsfiddle.net/leojavier/t83tb683/1/

Upvotes: 2

Maximillian Laumeister
Maximillian Laumeister

Reputation: 20359

I heard you like intervals, so let's get an interval to control your interval so you can run an interval while you run an interval.

The following live demo has a "blink interval" running at 500ms, and a "pause interval" that controls the blink interval, running at 2000ms:

function blink() {
    $("#light_3_1").animate({
        "opacity": 0
    }, 400).animate({
        "opacity": 1
    }, 400);
}

var blinkInterval;
var pauseInterval;
var blinking = true;

$(document).ready(function () {
    blinkInterval = setInterval(blink, 500);
    pauseInterval = setInterval(toggleBlink, 2000);
});

function toggleBlink() {
    if (blinking) {
        clearInterval(blinkInterval);
        blinking = false;
    } else {
        blinkInterval = setInterval(blink, 500);
        blinking = true;
    }
}
#light_3_1 {
    width: 150px;
    height: 150px;
    background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="light_3_1"></div>

JSFiddle Version: https://jsfiddle.net/kv18e1sL/1/

Upvotes: 3

Related Questions