setTimout
requires a specific syntax in order to function correctly. For more information, refer to the comprehensive JavaScript documentation provided by Mozilla: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#Syntax
Below is a simple example:
saySomethingAfter(5);
function saySomethingAfter(second) {
setTimeout(saySomething, second * 1000);
}
function saySomething() {
console.log("Something");
}
If your question is "How can I automatically change a page in Javascript?" using setTimeout
, consider the following requirements:
- To change a page → open a new URL (see: Open URL in same window and in same tab)
- Automatically using
setTimeout
→ ensure correct syntax
function changePage(url) {
window.open(url, "_self");
}
function changePageAfter5sec(url) {
setTimeout(function() {
changePage(url)
}, 5000);
}
changePageAfter5sec("https://stackoverflow.com")
Alternatively, you can use a functional JavaScript approach:
function changePage(url) {
return () => {
window.open(url, "_self");
}
}
function changePageAfter(second) {
return (url) => {
setTimeout(changePage(url), second*1000);
}
}
const changePageAfter5sec = changePageAfter(5);
changePageAfter5sec("https://stackoverflow.com")