Is there a way to prevent a web page from refreshing automatically for a defined duration using programming techniques?

I am currently working on a specific mobile wireframe web page that includes a timer for users to answer a question after the web content body has loaded. There are two possible outcomes when answering the question: 1) If the user fails to answer in time, the server will consider it a failure. 2) If the user answers before the question time expires, it will be considered a success.

My challenge is preventing users from rerunning the script that counts down the seconds left. I want to avoid any frontend communication with the database after the question page has loaded, as it could lead to issues related to lost connection during answering. To address this, I have implemented a JavaScript script for timing as follows:

let iterator = 0;
const secondsMax = 15;
const elem = document.getElementById("secLeft");
elem.innerHTML = secondsMax ;

function timer() {
    setTimeout(function(){ 
        iterator++;
        elem.innerHTML = secondsMax - iterator;

        if(iterator === secondsMax) {
             // progress bar moves... moving onto the next question out of 5
             move();
             iterator= 0;
             
             // signal to evaluate the question...
             return;
         }
         
         timer();
     
     }, 1000);
}

I have come across suggestions similar to StackOverflow's recommendation of using AJAX to prevent reloading the page for receiving response from the server. However, my intention is to programmatically prevent users from refreshing on the frontend to avoid cheating (although I may not fully understand the usage of AJAX in this case). Are there any ideas or solutions you can offer? I am open to criticism, and if there is a better solution (as I am new to web technologies), please feel free to advise me accordingly.

Thank you in advance for your valuable time.

Answer №1

Firstly, it is essential to implement server-side validation in order to prevent cheating instances.

For instance, each question asked has a unique hash linked to its start time. By comparing the received answer with the corresponding hash, you can determine the time spent on answering the question.

On the client-side, you can save the start time for that specific question in the local storage. If the page finds a local storage entry for the current question's hash, it will initialize the timer with the saved start value.

const TIME_ALLOWED = 10e3; // 10 sec
const QUESTION_HASH = '1fc3a9903';
// start = localStorage.getItem(QUESTION_HASH) else
let start = Date.now();
let timeleft = document.getElementById('timeleft');

let timer = setInterval(() => {
  
  let timepass = Date.now() - start;
  if (timepass >= TIME_ALLOWED) {
    clearInterval(timer);    
    timeleft.innerText = 'Time is over';
    // localStorage.setItem(QUESTION_HASH, null)
    return;
  }
  let secs = (TIME_ALLOWED-timepass) / 1000 | 0;
  let mins = secs / 60 | 0;
  secs = secs % 60;
  if (secs < 10) secs = '0' + secs;  
  timeleft.innerText = `${mins}:${secs}`;
}, 500);

const answerQuestion = e => {
  if (Date.now() - start >= TIME_ALLOWED) return; // disallow answering
  clearInterval(timer);
  timeleft.innerText = 'Answer received';
  // localStorage.setItem(QUESTION_HASH, null)
}
Time left: <span id="timeleft"></span><br/>

<button onclick="answerQuestion()">Answer</button>

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

What is the best method for implementing pagination in Larvael with React using Inertia?

Is there a way to paginate in react using inertia with laravel? When pulling paginated data, I use the following code: $contacts = Contact::orderBy('name', 'asc')->paginate(10); return Inertia::render('Contacts/index', [ ...

Displaying a preloaded image on the canvas

Once again, I find myself in unfamiliar territory but faced with the task of preloading images and then displaying them on the page once all elements (including xml files etc.) are loaded. The images and references are stored in an array for later retrie ...

Extract only one term in PHP

I've searched high and low but haven't found a solution that fits my needs. All I want to keep is the word you. $words = "you,us,them,our"; $keep = "you,"; The code provided seems to do the opposite of what I need: $words = str_replace("$kee ...

Is there a way to align my two tables next to each other using CSS?

.page { display: grid; grid-template-columns: 1fr 1fr; grid-gap: 20px; } .items { float: left; } .secondItem { vertical-align: text-top; float: right; } .page-header table, th, td { border: 1px solid; display: block; background-color: ...

Issue occurred when attempting to send the STMT_PREPARE packet, with the Process ID being

I can't seem to figure out why this bug keeps happening. Here is the script I am using: foreach($brands as $brand){ // about 600items for this loop .... .... DB::table('mailing_list')->insert(array( &ap ...

How to send an html form with php, store it in a MySQL Database, and utilize Ajax and jQuery for

As a beginner in PHP form creation, I have been exploring various tutorials and combining different techniques to create my form. However, I am facing challenges as none of the tutorials cover everything comprehensively from beginning to end. While I beli ...

Inject an html <img> tag using an AJAX PHP call

Greetings everyone, I am currently in the process of developing a captcha maker using PHP with an Object-Oriented Programming (OOP) approach. The implementation involves a Captcha class responsible for generating the captcha image. You can find the complet ...

Having trouble processing the Firebase snapshot with Node.js

I have a question regarding a snapshot; ref.orderByChild("index").equalTo(currentIndex).once("value", function(snapshot) {}) After printing the snapshot with ; console.log(snapshot.val()); This is the output that gets printed; {'-LBHEpgffPTQnxWIT ...

Exploring data retrieval through relationships in the Yii PHP framework

Greetings, I am facing an issue with my database where I utilize a link table to establish connections between products and categories. The relational structure is as follows: Product ProductCategories Category Id Id ...

Utilize the left sidebar in Magento to showcase categories

Embarking on the journey of creating an e-commerce website using Magento 1.7 has been quite the challenge for me as a newcomer to the platform. I have written the following code in /app/design/frontend/default/default/layout/catalog.xml: <block type=" ...

Is there a way to pass a token variable from the main page to an iframe without relying on a post message?

I am seeking assistance on how to transfer a variable from a parent window to an iframe. My situation is as follows: I am working with 2 Angular5 applications named A and B . Application B is loaded within Application A using an iframe. The aut ...

What is the best way to retrieve data from a post api?

I am working with an API that retrieves data from a database. Here is the form I have: <form action="<c:url value="/getCandidateDetails"/>" method="post"> <div class="form-group"> <label for="masterId">Master Id:</ ...

Tips for identifying a range between two columns in MySQL

If I have a value, let's say 45. What is the best way to determine if this value exists in the database? The complication arises from having two columns like so: -------------------- range_from range_to -------------------- 10 ------------ 20 - ...

Transforming a React, Redux, and MUI Menu into an Electron Application

I'm in the process of transforming a web-based React + Redux + MUI application into an Electron app. The original app features a main AppBar with multiple dropdown menus, each containing menu items that interact with the app's Redux store. While ...

Guide to retrieving a user's current address in JSON format using Google API Key integrated into a CDN link

Setting the user's current location on my website has been a challenge. Using Java Script to obtain the geographical coordinates (longitude and latitude) was successful, but converting them into an address format proved tricky. My solution involved le ...

Continuously retrieving information from a database to display on a web page

Our team is currently developing a solution that requires a dashboard with basic views and charts that need to be updated every 10 seconds when active. Each user will have the same charts but showing filtered information. In order to achieve this function ...

What steps should I take to resolve the issue where Angular project error states that the data path "/polyfills" must be a string?

I am struggling with deploying my Angular app to Firebase and/or running it successfully locally using NodeJS version 18. To access the package.json and source code, you can click on this link: https://github.com/anshumankmr/jovian-genai-hackathon/blob/mas ...

Conflicts between Bootstrap Validator and Ajax.BeginForm in Partial Views of MVC

My current issue involves using Ajax.BeginForm to post data on a form without refreshing the entire page. The goal is to validate a textbox - if it has a value, then the data should be posted; otherwise, a validation message should be displayed. However, I ...

PHP: Managing Multiple Submission Buttons

Seeking input on the best approach for this situation: When dealing with multiple submit buttons, is it more efficient to use separate FORMS for each button or is it acceptable to have only one form and determine which button was clicked? Appreciate your ...

Updating JSON in JavaScript

I am striving to structure a JSON object in the following manner: {"tokenId":1,"uri":"ipfs://bafy...","minPrice":{"type":"BigNumber","hex":"0x1a"},"signature":"0 ...