Allow a Function to be called only after a time that page has been loaded

Asked

Viewed 168 times

1

I wonder if there’s a way to allow a Function to be called only after a few seconds. Example I have a function that emits sound when a new message appears it is called, but when I restart the page the Function is called right from the beginning, the notification should stay more the sound should not be called, only when a message arrives there yes it should be called.

So let’s say that you received an msg and will not read now, but every time that msg is greater than 1 it calls the function emitSom(), but I just want you to call this Function when the ajax stay working, but it comes back with the notifications(so far so good)and calls the sound Function, that is every time you change pages the same calls the function that ends up irritating.

Code:

Ajax function:

function notificarNMsg(id, tp_usuario, codigo, ultimos_id) {
    ids = ultimos_id;
    $.ajax({
        url: 'pages/atualizacoes.php', /* URL que será chamada */
        type: 'POST', /* Tipo da requisição */
        data: {ANLid_usuario: id, ANLtp_usuario: tp_usuario, ANLcodigo: codigo, ultimos_id: ids},
        dataType: 'json', /* Tipo de transmissão */
        success: function (data) {
            if (data.msg_nao_lidas >= 0) {
                if (data.ids == 0) {
                    $("#areaMsg").html('<span></span>').removeClass("vibrarMsg");
                } else if (data.ids !== 0 && data.msg_nao_lidas > 0) {
                    qtd_existente = $("#areaMsg  span").text();
                    if (qtd_existente == '') {
                        qtd_existente = 0;
                    }
                    qtd_msg_total = parseInt(qtd_existente) + parseInt(data.msg_nao_lidas);
                    $("#areaMsg").html('<span>' + qtd_msg_total + '</span>').addClass("vibrarMsg");
                    acionarAlerta('./sons/nv_msg.wav');
                    trocarTituloPorTempo('- (' + qtd_msg_total + ') Mensagem');
                    if (ids != 0) {
                        ids = ids + ',' + data.ids.join(",");
                    } else {
                        ids = data.ids.join(",");
                    }
                }
            }
            notificarNMsg(id, tp_usuario, codigo, ids);
        }
    });
}

Function that should be "Created" after a few seconds.

function acionarAlerta(caminho) {
    var som = new Audio(caminho);
    som.play();
}
  • See more about setTimeout(), something like: setTimeout(function(){alert("minha msg")}, 500), the function will be called as soon as it gives the time(500, in ms). See more: http://www.w3schools.com/jsref/met_win_settimeout.asp

  • Yes I know that, but that’s not quite it, like in the beginning a Function calls another Function that emits sound, only it is programmed not to be called until it passes some 30 seconds.

  • Can you explain the question better? It’s unclear...

  • I tried... see there.

  • Put the Function code and what you call it, so people can help you better.

  • Ready! I think it’s better now.

Show 1 more comment

2 answers

1

Wait for the event DOMContentLoaded document - this will indicate that the page has been completed. After that, you can implement a Timeout to be executed after N milliseconds.

// Aguarde a finalização da carga da página:
document.addEventListener("DOMContentLoaded", function(event) { 
    // Dispare um evento daqui a 5 segundos (5000 milissegundos):
    window.setTimeout(function () {
        // Redirecionando...
        location.href = "https://www.google.com";
    }, 5000);
});
  • But I don’t want to redirect, what I want is that it emits sound only when the user is eating the open page, not when it updates the page with the new unread msgs.

  • @Romariopires this is just an example of implementation. Feel free to change the code and make your calls.

  • Okay, but so I don’t want javascript to call, just ajax, you know? Like Ajax calls when to load the page but Function does not exist, it is only created after 5 seconds, ai dps of that time ajax calls again, ai sim o acionarAlerta funciona!

  • @Romariopires the anonymous function in the case of Success has not yet been instantiated, but nothing prevents you to call notificarNMsg().

  • I don’t understand '-'

  • @Romariopires I’ll be back soon and continue the explanation =)

  • 1

    Where is Location.href substitues by the function you want to create after the page loaded (triggerAlerta(path)). It should be as intended.

Show 2 more comments

0

You can listen to the cargo event from window, after that wait a while (using the function setTimeout) and then call its function.

window.addEventListener("load", function load(event) {
    setTimeout(function () {
        acionarAlerta("seu_caminho");
    }, 5000);
});

or

window.onload = function (event) {
    setTimeout(function () {
        acionarAlerta("seu_caminho");
    }, 5000);
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.