Wait a certain period to run a Javascript function?

Asked

Viewed 1,379 times

1

Is there any method that makes a function run after a certain time? What I need is for the function below to run after a period of time, because the ID it searches for is only available after a time we are on the page.

var func = document.getElementById('olvideo_html5_api').src;
alert(func);
window.location.href = +func

1 answer

2


Use setTimeout() to perform a function after the specified time (in seconds):

tempo = 10; //especifique aqui os segundos
tempo = tempo*1000;
setTimeout(function(){
    var func = document.getElementById('olvideo_html5_api').src;
    alert(func);
    window.location.href = func;
}, tempo);

Or you can specify the time directly in the function:

setTimeout(function(){
    var func = document.getElementById('olvideo_html5_api').src;
    alert(func);
    window.location.href = func;
}, 10000); // o tempo é dado em milisegundos
  • The function of capturing the ID worked perfectly, but could not redirect the site to the captured link.

  • The first method is more interesting because of its second to millisecond converter.

  • @Diegoqueiroz His mistake was in window.location.href = +func;... See the correction I made in the reply: window.location.href = func;

  • It worked perfectly, I thought that in every variable link manipulation it was necessary the "+" before the same.

Browser other questions tagged

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