Reputation: 97
Basically I'm trying to make a skull flicker over a persons face, I've achieved it flashing up once. But the effect I'm trying to achieve is that it looks more organic and random. Here's the basic structure:
function flicker() {
var maxFlick = 6,
amount = Math.round(Math.random() * maxFlick),
running = false;
function showHide() {
$flicker.show();
running = true;
setTimeout(function() {
$flicker.hide();
running = false;
}, 100)
}
for (i = 0; i < amount; i++) {
if(!running) {
showHide();
}
}
}
setInterval(flicker, 4000);
I had presumed that running a for loop with a random amount statement would produce the desired effect, but it's still only flashing up once every 4000milliseconds as previously. Any pointers?
Upvotes: 1
Views: 861
Reputation: 97
With the help of Regent and this fiddle I came up with the answer:
function flicker() {
var maxFlick = 6,
amount = Math.round(Math.random() * maxFlick),
delta = 2,
timer;
var doneFlicks = 0;
var flickInterval = setInterval(showHide, timer);
function showHide() {
timer = Math.round((Math.random() + delta) * 100)
$flicker.show();
var hide = setTimeout(function() {
$flicker.hide();
doneFlicks++
}, 20)
if (doneFlicks == amount) {
clearInterval(flickInterval);
}
}
}
setInterval(flicker, 3000);
This produces a randomised flicker effect that's called every 3 seconds - perfect for a horror film effect!
Thanks again to Regent for all the help!
Upvotes: 2