Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript setInterval every 5 seconds

I would like to set an interval of 5 seconds between each alert. Found this thread:

setInterval(function() {
    alert("Message to alert every 5 seconds");
}, 5000);

But where do I put the setInterval() in order to alert every 5 seconds?

$(window).scroll(function() {
    if (checkVisible($('#footer'))) {
        alert("I DONT SEE A FOOTER");
    } else {
        alert("EUREKA - I SEE A FOOTER");
    }
});

function checkVisible(elm, eval) {
    eval = eval || "visible";
    var vpH = $(window).height(), // Viewport Height
        st = $(window).scrollTop(), // Scroll Top
        y = $(elm).offset().top,
        elementHeight = $(elm).height();

    if (eval == "visible") 
        return ((y < (vpH + st)) && (y > (st - elementHeight)));

    if (eval == "above") 
        return ((y < (vpH + st)));
}

Many thanks in advance.

like image 659
Hbaecklund Avatar asked Feb 29 '16 13:02

Hbaecklund


Video Answer


2 Answers

You can put in load function

$(document).ready(function()
{
     setInterval(function() {
        alert("Message to alert every 5 seconds");
     }, 5000);
});
like image 107
praveen Avatar answered Oct 07 '22 19:10

praveen


Repeating every 5 seconds, started by scroll event:

var myTimer;

function showAlert(inString){
    alert(inString);
    myTimer = setTimeout(function() {
        showAlert();
    }, 5000);
}

$(window).scroll(function() {
    clearTimeout(myTimer);
    if (checkVisible($('#footer'))) {
        showAlert("I DONT SEE A FOOTER");
    } else {
        showAlert("EUREKA - I SEE A FOOTER");
    }
});

You can see that I'm using clearTimeout(myTimer) to delete the previous timer, which avoids us starting the timer too many times. For this to work, we have to store the timer first - I've done it in the myTimer variable.

Shows 5 seconds after scroll event but only once:

function showAlert(inString){
    myTimer = setTimeout(function() {
        alert(inString);
    }, 5000);
}

$(window).scroll(function() {
    clearTimeout(myTimer);
    if (checkVisible($('#footer'))) {
        showAlert("I DONT SEE A FOOTER");
    } else {
        showAlert("EUREKA - I SEE A FOOTER");
    }
});
like image 20
millerbr Avatar answered Oct 07 '22 19:10

millerbr