Question

I'm trying to create a "horror" style flickering effect using jQuery. A box on the page loads, seems normal (i.e. doesn't do anything for a few seconds), flickers like scary lights in a horror house, and then it replaced with a new box.

I've tried this: http://jsfiddle.net/LRvVm/

$("#box").delay(5000).hide().delay(500).show().delay(500).hide().delay(500).show().delay(500).hide().delay(500).show().delay(500).hide(
function(){
         $("#box2").fadeIn("slow");
         });

But it doesn't seem to work, and to make matters worse, the jQuery website is down at the moment, so I can't even research what I'm doing wrong.

Was it helpful?

Solution

The problem is, you are using hide() and show() which does not make use of queue based executions so your .delay() does not have any effect.

Use queue(animation) based methods like hide('fast') / show('fast') / fadeOut('fast') / fadeIn('fast') instead

$("#box").delay(5000).hide('fast').delay(500).show('fast').delay(500).hide('fast').delay(500).show('fast').delay(500).hide('fast').delay(500).show('fast').delay(500).hide(

function () {
    $("#box2").fadeIn("slow");
});

Update:

function flicker(count, callback, current) {
    current = current || 0;

    $("#box")[current % 2 == 0 ? 'hide' : 'show']();

    setTimeout(function(){
        if (count * 2 <= current) {
            callback();
            return;
        }
        flicker(count, callback, current + 1)
    }, 500);
}

setTimeout(function () {
    flicker(3, function () {
        $("#box2").fadeIn("slow");
    })
}, 1000)

Demo: Fiddle

OTHER TIPS

You can use toggleClass.

Here is an example http://jsfiddle.net/LRvVm/4/

It needs to be tweaked slightly because it is technically infinite recursion!

var interval = 1000;

flicker();

function flicker()
{
    $("#box").toggleClass('on');
    setTimeout(flicker, interval)
}

You can tweak your on/off css however and it should work well. You can even adjust the speed like the fiddle below: http://jsfiddle.net/PTQVt/2/

You could also use a setInterval in order to accomplish this, and avoid a long string of jQuery methods. Here is an example to look at.

var x = 0;


window.onload = function () {
    window.timer = setInterval(flicker, 200);
};

function flicker () {
    if (x % 3 === 0) {
            document.body.style.display = 'block';
            x++;
    } else {
            document.body.style.display = 'none';
            x++;
    }
}

I had the same problem and solved it with a combination of setInterval and setTimeout, like this:

function flicker(htmlElem) {

    var parpadea = setInterval(function(){htmlElem.toggleClass('hidden');}, 200);
    setTimeout(function(){clearInterval(parpadea);}, 3000);

}

the hidden class is simply display:none this would show the image (htmlElem) flickering each 200 ms for three seconds

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top