Explanation
You need to pass a function reference (or a string of JavaScript code) to setTimeout
, in order for it to be executed when the timeout is reached.
In your code, you were immediately calling the function (which doesn't return
anything anyways, so its return value is undefined
...so nothing will execute when the timeout is reached).
Approach 1
Use an anonymous function that runs your code:
setTimeout(function () {
redirectLink(url);
}, 5000);
function redirectLink(url) {
window.location.replace(url);
}
Approach 2
Make your redirectLink
function return a function and call it like you originally did:
setTimeout(redirectLink(url), 5000);
function redirectLink(url) {
return function () {
window.location.replace(url);
};
}
Approach 3
You could use .bind()
:
setTimeout(redirectLink.bind(null, url), 5000);
function redirectLink(url) {
window.location.replace(url);
}
Note that .bind()
requires a polyfill for some older browsers.
References:
setTimeout
: https://developer.mozilla.org/en-US/docs/DOM/window.setTimeoutFunction.prototype.bind
: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind