This block is part of the validation of a form. This part is where after validating the form without errors it shows a message and after 5 seconds it redirects to another page using setTimeout
and window.location.href
. It works correctly, only that it does not do it taking into account the indicated seconds.
Where this error?
const esExito = true;
if(esExito) {
const dire = "wishlist.html";
$form.className = 'oculto';
document.querySelector('#exito').className = '';
setTimeout(redireccionar(dire), 5000);
}
function redireccionar(dire) {
window.location.href = dire ;
}
I recommend leaving it as follows, given the setTimeOut documentation from developer.mozilla.org
Greetings and write any questions.
The problem is that you are calling the function with the call() method. This causes the function to be called (executed) at that very moment. The solution is to insert the function inside setTimeout(an anonymous function) or call a reference of this function.
It does not take into account the indicated seconds because you are executing the function
redireccionar(dire)
, the return isundefined
when the timeout waits for a type,function
I will place an example so that you understand more:The ideal is that your function waits for a parameter and returns a function, this is known as Clousure or Clausuras , see the following example:
Your code would look like this:
You are adding the function in your same definition block of the first function, here I add a correction and it is already tested.