How to insert a set time into a function

5

The function of this code below and after I click on a submit of a form it redirects to another page this works now only need it only redirects to another page after, 5 seconds someone knows how to do this very little javascript handling?

$("form").submit(function(){
  window.location = 'minha URL';
}
    
asked by anonymous 16.01.2017 / 23:42

2 answers

4
$("form").submit(function(){
  setTimeout(function(){ window.location = 'minha URL'; }, 5000);
}
    
16.01.2017 / 23:54
5

You can use setTimeout()

Do this:

$("form").submit(function(){
    setTimeout(function() {
        window.location = 'minha URL';
    }, 5000);
}

After clicking the button will execute the function setTimeout() that receives a function to be executed and the time in milliseconds, after that time it performs the function passed.

You can still assign the function to a variable to be able to cancel later, for this you would use the function clearTimeout() receiving the variable with the function to be canceled:

$("form").submit(function(){
    var timeout = setTimeout(function() {
        window.location = 'minha URL';
    }, 5000);

    //Parar timeout
    clearTimeout(timeout);
}
    
16.01.2017 / 23:56