Using Javascript, create a loop that navigates between two different pages and add a timer on one of them

How can I create a while loop that spans across 2 HTML pages or use a prompt to ask a question? If the wrong answer is provided, I would like to be redirected to another HTML page which will display for 5 seconds before returning to the prompt.

This is my current attempt at coding:

<!DOCTYPE html>
<html>
<body>
    <script>
        var pass;
            pass = prompt("The corret answer is 1");
        if (pass == "1") {
            document.location.href = "https://stackoverflow.com/questions/40539097/redirect-user-to-another-html-page-if-the-condition-is-true";
        } else {
            setTimeout(function(){
              window.location.href = 'prova2.html';
         }, 5000);
        }
</script>
    <body>
</html>

The issue I'm facing is that the "prova2.html" page only appears after 5 seconds. How can I make it visible for the entire duration?

Answer №1

However, your code operates in a way where if the prompt result is '1' it redirects to SO, otherwise it initiates a timer that redirects to prova2 after 5 seconds.

If you desire the specific behavior you are discussing, the solution is to redirect to prova2.html right away and in the code for prova2.html, establish a timeout function to redirect you back after 5 seconds:

In your original.html file (or whatever name it has for you):

<!DOCTYPE html>
<html>
  <body>
    <script>
      var input = prompt("Please enter the correct answer: ");
      if (input == "1") {
        document.location.href = "https://stackoverflow.com/questions/40539097/redirect-user-to-another-html-page-if-the-condition-is-true";
      } else {
        document.location.href = 'prova2.html';
      }
    </script>
  <body>
</html>

In your prova2.html file:

<!DOCTYPE html>
<html>
  <body>
    <script>
      setTimeout(() => {
        document.location.href = 'original.html';
      }, 5000)
    </script>
  <body>
</html>

Answer №2

This demonstration in prova2.html demonstrates a unique way of navigating using the session history of the browser:

<!DOCTYPE html>
<html>
<body>
    <script>
      document.addEventListener("DOMContentLoaded", function(event) {
        setTimeout(function(){
            history.back();
            //window.location.href = 'previous.html';
          }, 5000);
        });
    </script>
      <p>After 5 seconds of page load, you will be redirected back.</p>
    <body>
</html>

Source: https://developer.mozilla.org/en-US/docs/Web/API/History/back

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A guide on how to navigate the parent window from a child window

When using my application, I have a function that opens a new window like this: window.open("www.example.com"); Within the new window, there is a button. Upon clicking this button, the new window should close and then redirect the parent window to a diff ...

"Utilize the most recent version of Uploadify to easily upload your

I am having trouble uploading a video using the latest version of uploadify. Here is my code: HTML: <form enctype="multipart/form-data" class="form-part" action="form.php" method="post"> <input class="uplodify" id="file_upload" type="file"/ ...

React-navigation installation in React Native project failed due to ENOENT error - file or directory does not exist

Encountering errors during the installation of react-navigation in my react native project using npm install @react-navigation/native https://i.sstatic.net/uKiPQ.png The installation process reaches halfway, pauses for a few minutes, and then displays an ...

Enhance your website with various map types using Google Maps JavaScript API v3

Is there a way to include Hybrid, Satellite, Terrain, and Physical View Modes in a Google Map created using the Gmap JavaScript API v3? This is what my current code looks like: var myLatlng = new google.maps.LatLng(47.283902, 11.526825); var mapOptions = ...

What is the reason behind having to include index 1 in the childNodes array when trying to access the initial child element?

I'm working on a JavaScript function that is supposed to display the text entered into an input field. Here is the code I have written: <head> <script type="text/javascript"> function showText() { var input = document. ...

Execute an AJAX call to remove a comment

Having some trouble deleting a MySQL record using JavaScript. Here is the JavaScript function I am trying to use: function deletePost(id){ if(confirm('Are you sure?')){ $('#comment_'+id).hide(); http.open("get","/i ...

Bypassing angular's dependency injection by utilizing a universal object

Recently, I came across some code that utilizes a global object to store angular services. These services are attached to the global object within the run function of the angular module. It made me wonder, could this approach potentially lead to issues i ...

Creating a Website Optimized for Mobile Devices

As a beginner web developer, I am in the process of creating a mobile-friendly website system. Currently, I am utilizing Bootstrap for responsiveness, PHP5, MySQL, and occasionally Ajax/JQuery. Recently, I came across JQuery Mobile. While I have been usin ...

Get data from ajax request in controller

I'm currently working with this JavaScript code snippet: var formData = new FormData($('#formSlip').get(0)); formData.append('myList', JSON.stringify(tests)); The variable tests holds a list of objects. I am making an AJAX PO ...

Ensure that the table tag in testWeb(jspackage.JSAssignmentDiscount) contains exactly 3 rows and assess whether it complies with the CSS criteria for tables and table rows

Criteria: The table must include the product name, product price, and season information. The product name and product price should be input text boxes labeled with name and price respectively. The season selection should be a dropdown menu labeled with s ...

Why isn't the Angular Google Maps Displaying in my Template View?

After configuring Angular Google Maps and following the provided steps, I am facing an issue where the map is not loading on the directive without any error. Below is the code snippet: Controller app.controller('MapCtrl', [ '$scope&apo ...

When the clearOnBlur setting is set to false, Material UI Autocomplete will not

I recently encountered an issue in my project while using Material UI's Autocomplete feature. Despite setting the clearOnBlur property to false, the input field keeps getting cleared after losing focus. I need assistance in resolving this problem, an ...

Tips on efficiently inserting numbers into the names of copied input elements

I've been struggling with a problem for hours now and I need help... I'm trying to change the names of my automatically cloned inputs. Here is the snippet of my HTML code: <form id="dodawanie" action="" method="post"> <div class= ...

CSS radio button not showing up on Safari browser

I am encountering an issue with my vue app where it functions correctly on Google Chrome but experiences problems on Safari. Specifically, the issue arises with components containing radio buttons. Upon clicking on a radio option, the selected color (blue) ...

Manually adjust rotation in Three.js by clicking

I am looking to initiate an animated rotation of an object by clicking a button. I have a basic understanding that the render function operates as an infinite loop and that adding 0.1 to cylinder.rotation.x continuously rotates the object. My goal is to ...

Experience the power of Kendo UI Date Picker combined with AngularJS. When the datepicker is initialized, it starts

Check out my code snippet below: When the datepicker loads initially, it appears empty. However, if you remove ng-model from the directive template, the datepicker displays its initial value correctly. Yet, changing the selected date does not mark the fo ...

Ways to customize the datetime-local format in an HTML input field

When dealing with the HTML input of datetime type, consider the following: Datefield: <input type="datetime-local" data-date="" data-date-format="DD MMMM YYYY, h:mm:ss"> The script below includes important code. $("input").val(moment().format(&apo ...

Issues with jqGrid's grid grouping feature not functioning as expected

Is there a way to group my data by the name element and hide the grouping column as shown in this example ()? Even though all 3 columns are present on the page, I specifically want to hide the group column (name). Additionally, it seems that the main col ...

Utilize the map function on an array object to present data in a table using React framework

My parent component passes an array object that looks like this: https://i.sstatic.net/Nqh81.png I want to organize these values into a table with the keys in one column and their corresponding values in other columns. The desired format is shown here: ht ...

transforming blog into a data URL

I've been struggling to convert an image blob into a data URL using Vue.js, but I keep encountering this error: 'Error in v-on handler: "TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provide ...