Please refrain from continuously refreshing the JavaScript file within Django templates

Is there a way to prevent the countdown timer from resetting when refreshing data on an HTML page? I want to update the data without interfering with the countdown timer.

app.js

var count = 8
var counter = setInterval(timer , 1000)

function timer(){
    count = count-1
    if (count <= 0)
    {
        clearInterval(counter);

        return window.location.href = urlFromDjango
    }
    document.getElementById("timer").innerHTML= count + " secs";
}

index.html

{% load static %}
<head>
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
    <link rel="stylesheet" href="{% static 'css/app.css' %}">
    <script src="{% static 'js/app.js' %}"></script>
</head>
<script>
    var urlFromDjango = "{% url 'app:result' %}"
</script>

<body>
     <h1 id="timer"></h1>
</body>

<h1>{{user.username}}</h1><br>
<h2>score -{{user.userextend.score}}</h2>
<form action="{% url 'app:detail' quiz_id=que.quiz.id question_id=que.id %}" method="post">
     {% csrf_token %}
     {% for choice in que.answer_set.all %}
         <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}">
         <label for="choice{{ forloop.counter }}">{{ choice.answer }}</label><br>
     {% endfor %}
     <button><a href="{% url 'app:detail' %}">Next</a></button>
</form>

Answer №1

In order to ensure the information is retained even after refreshing the page, it is essential to store that data in a secure location. One reliable method is to save it either in cookies or local storage. Here's a simple illustration:

let count = parseInt(localStorage.getItem("count-" + window.location.pathname)) || 8;
let counter = setInterval(timer, 1000);

function timer(){
    count = count-1;
    localStorage.setItem("count-" + window.location.pathname, count);
    if (count <= 0){  
        clearInterval(counter);
        return window.location.href = urlFromDjango;
    }
    document.getElementById("timer").innerHTML = count + " secs";
}

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

Is it possible to create a component with a button that triggers the rendering of a different component?

I am struggling to implement an 'edit' button within a component that, upon clicking, should display a separate component known as a 'client edit modal'. I'm facing challenges in figuring out how to achieve this functionality. The ...

Executing a Javascript function post AJAX page loading

I'm not a coding expert, so I hope my question is still clear. Essentially, I have an index.php page with filters (by project, year, month) that send variables to filterData.php after clicking submit. These variables are then used in SQL statements t ...

Failed Heroku deployment due to error with django.utils causes release to crash

After updating my python code to Django 4.0, I encountered the task of removing and updating some deprecated code such as "ungettext_lazy" and similar. While the code compiles locally without any issues, pushing it to Heroku resulted in the following erro ...

Removing the Tawk.to integration in React Redux using external JavaScript

Seeking help with integrating the Tawk.To Widget into my React APP. The widget (javascript) loads successfully when the page is first opened, but remains present when navigating to another page. How can I properly unmount this script when moving to a diff ...

Problem with the content-editable attribute

My goal is to make each div with the class .edit editable by adding the contenteditable property: $(document).ready(function() { $(".edit").attr("contenteditable", "true"); }); However, after applying this, I found that clicking on a div with content ...

Sending post forms securely using HTTPS instead of HTTP

Here is the code snippet located on : <form id="MainForm" name="MainForm" method="post" action="xyz.aspx"> We now want to redirect the user to . However, we are unable to use the full URL as we need to implement the same code across all environment ...

discovering identical patterns within a collection of elements

Attempting to identify matching patterns for the string input by the user in a textbox. The code works well in most cases, but there are instances where it does not provide all the required results. Below is a link to a jsfiddle displaying the functioning ...

Removing a similar object from an array using JavaScript

Working on a d3 force graph, I aimed for smooth updates using the method shown in the Modifying a Force Layout example. However, my goal was to achieve dynamic updating behavior unlike the static example provided. After calling initializeGraphData(json); i ...

Using JSF components `h:inputFile` and `f:ajax` for file input

I'm feeling a bit confused. I wanted to create a simple example where we can upload a file from an XHTML page and display something.jpg while the file is being uploaded. Here's what I did: <h:outputScript library="javascript" name="showProgre ...

Ways to restrict Firebase Firestore Read operations in React JS by utilizing the Snapshot technique

I have two main queries here. (1) I have been attempting to find a solution for limiting the read from Firestore, however, I have not been successful in implementing the limit() function with the snapshot method. We do not want to completely rewrite the f ...

What is the method to activate a select event on a particular row using Google visualizations?

Currently, there is a single table where clicking on a row should simulate the same action on another GV table. The code for the listener is as follows: $(".mytable tbody tr td").click(function() { var colIndex = $(this).parent().children().index($(th ...

Is there a way for me to choose multiple checkboxes simultaneously?

I have a dynamically created HTML table with checkboxes added for each row. $.each(data, function(id, value) { rows.push('<tr><td><input type="checkbox" autocomplete="off" class="chkbox" name="chkbox" value="'+value.site+' ...

Add a text to the values in a column of a table when the IDs are the same

I am working on a project that involves updating a table based on a data change. The table has a column for ID and when the ID matches a specific variable, I need to append the word 'Updated!' next to it in the table cell. However, the code I hav ...

Choose an element at random

I am trying to figure out how to select all div elements with the same class of "dot" under a parent div in JavaScript. Here is an example structure: <div id="dots"> <div class="dot"> . </div> <div class="dot"> . </div> ...

Video playback disabled on hover in Chrome browser

I have added videos to a search results page. When the user hovers over the video, I want to show a preview of it in a separate container and start playing the video. $(".videoSearchResults video").mouseenter(function () { var container = document.cre ...

Integrating component names into a tag in React

I've encountered a similar issue before, but unfortunately, the suggested solutions aren't working for me. I suspect it might have something to do with how I am conditionally rendering components. Essentially, I have a selection of choices for th ...

How can I append the current query string to a URL within a Django template?

Upon loading a page, I wish to add the link "sameLink" with the containing page's query string. The URL in question is: somedomain/reporting/article-by-month?variable1=2008 Any suggestions on how to achieve this? ...

Implementing a method to display HTML tags within text in a React application

I have been working on a text highlighting feature, and I have successfully detected the selection. Currently, I have something like Te<span>x</span>t within a string, represented as an array: ["Te", "<span>", "x ...

Adding the ability to export CSV files from Bootstrap Table to an Angular 15 project

Struggling to incorporate the Bootstrap-table export extension into my Angular project without success so far. Visit this link for more information Any assistance or examples would be greatly appreciated. Thank you in advance! This is what I have tried ...

Is it possible to utilize the jquery form plugin for uploading files in ASP.NET MVC using Ajax

I'm utilizing the Jquery Ajax Form Plugin for uploading a file with the following codes: AuthorViewModel public class AuthorViewModel { public int Id { get; set; } [Required(ErrorMessage = "{0} field cannot be left empty!")] [Display(Na ...