1

Trying to get the code to automatically change page using setTimeout, but I do not get it to work.

setTimeout()(page3, 500);

function page3() {
  changepage3('automatic')
}

This is what my code looks like right now, but I am suspecting that this is not enough. Anyone knows what is missing?

Constantin Chirila
  • 1,979
  • 2
  • 19
  • 33
E.B
  • 11
  • 2
  • 5
    Remove the first `()`, it should be `setTimeout(page3, 500)`. If JS code ever doesn't work as you expect, check the console by pressing F12. There will more than likely be an error you need to debug. Also note that refreshing content every 0.5 seconds seems far too quick. – Rory McCrossan Oct 03 '18 at 12:34

3 Answers3

2

try this one

function page3() {
  changepage3('automatic') 
}

setTimeout(page3, 500);
Harsh Metrey
  • 133
  • 5
  • function declaration can be written after theyr calls: https://repl.it/@enguerran/ShockedSupportiveFrontpage – enguerran Oct 03 '18 at 13:15
0

setTimout needs a specific syntax to work, check it out on the best JavaScript documentation by Mozilla: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#Syntax

Here is an example

saySomethingAfter(5);

function saySomethingAfter(second) {
    setTimeout(saySomething, second * 1000);
}

function saySomething() {
    console.log("Something");
}

Your question is "How can I automatically change a page in Javascript?" using setTimeout. Let's analyse the needs:


function changePage(url) {
  window.open(url, "_self");
}

function changePageAfter5sec(url) {
  setTimeout(function() {
    changePage(url)
  }, 5000);
}

changePageAfter5sec("https://stackoverflow.com")

Another way using beautiful functional JavaScript:

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")
enguerran
  • 3,193
  • 3
  • 26
  • 42
0

You have 2 major problems in the code snippet provided:

  1. That is not correct setTimeout() syntax - thus it doesn't actually work.
  2. Even if it did work, it would call 1 function that uses another function which doesn't exist thus breaking the code.

fix problem number 1:

window.setTimeout(changePage, 5000);

now we have a running timeout that will trigger 5000 milliseconds after initiation(usually). so let's fix problem 2 and let changepage() call an actual proper url opening function:

function changePage(){
    window.open(urlOfPage3);
}

Finally a simpler version with an anonymous callback function in the setTimeout:

window.setTimeout(function(){
    window.open(urlOfPage3);
}, 5000);
aviya.developer
  • 3,343
  • 2
  • 15
  • 41