Search code examples
javascriptjqueryanimationblink

Eye blink timer


I'm creating this website with few mascots and I'll implement a "eye blink timer" where I'll make every mascot blink.

My question here is: how do i implement (and how long it is?) the delay between blinks and the blink itself, on any language (i'll probably use Javascript, but it doesn't matter right now).

Is there any resource about a "blink algorithm" or something like that?

Edit: I know how to use setTimeout and setInterval, my question here is more about the algorithm than the implementation itself.


Final result:

var blink = {
    delay: function() {
        return Math.random() * 8000 + 2000;
    },
    duration: function() {
        return 100 + Math.floor(Math.random() * 100);
    },
    blinkAgain: function() {
        return (Math.random() < .2);
    },
    betweenBliks: function() {
        return blink.duration() / 2;
    }
};

$.fn.blink = function(continueBlinking) {
    var $element = $(this);

    // Star the blink
    $element.addClass('blink');

    // Finish the blink
    setTimeout(function() {
        $element.removeClass('blink');

        // Change of blinking again
        if (blink.blinkAgain()) {
            setTimeout(function() {
                $element.blink(false);
            }, blink.betweenBliks());
        }
    }, blink.duration());

    // Continue blinking?
    if (continueBlinking) {
        setTimeout(function() {
            $element.blink(true);
        }, blink.delay());
    }
};

Solution

  • The rate of blinking varies, but on average the eye blinks once every five seconds. That's
    equal to 17,000 times each day or 6.25 million times a year.

    Source

    Assuming you have a function blink that does the "blinking", you might simply want to do something like this:

    setInterval(blink, 5000); // 5000ms i.e. 5s
    

    If you want a little more "Randomness" in your blinking, you could do the following:

    function blink() {
        [...] // The blinking
        setTimeout(blink, 5000 + ((Math.random() - 0.5) * 2000));
    }
    

    Which will, if my calculations are correct, call the blink function in a random manner between 4000 and 6000ms, given that Math.random() returns a value between 0.0 and 1.0, therefore "Math.random() - 0.5" will be between -0.5 and 0.5. That times 2000 will result in a value between -1000 and 1000.