Need help sharing a Javascript variable locally between files - javascript

I've been developing a speed test typing game for some time now, and I've been stuck on how to take the time you finish from one HTML page (the game itself) to an alternate one (the score page). I've been trying to use import{} export{}, but I'm not 100% sure how they function and so they haven't exactly worked. I'll attach both the game HTML and Javascript code and the score HTML and Javascript code.
<!-- THIS IS THE HTML PAGE FOR THE GAME -->
<!DOCTYPE html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Typeboss || Speed Typing Web Game</title>
<link rel="stylesheet" href="../css/gamestyle.css">
<style>
#import url('https://fonts.googleapis.com/css2?family=Cabin:wght#500&display=swap');
</style>
<script src="../js/gamescript.js" defer></script>
<script src="../../main/js/mainscript.js" type="module" defer></script>
<script src="./scorescript.js" type="module" defer></script>
</head>
<body>
<div id="all">
<div id="stats">
<h1 id="bossHealth" class="stat">BOSS HEALTH:</h1>
<h1 id="time" class="stat"><span id="minutes">0</span>:<span id="seconds">00</span></h1>
</div>
<div id="boss">
<img src="../imgs/boss.png" width="400px" height="400px" id="bossSprite">
</div>
<div id="input">
<h3 id="outcome"></h3>
<center><p id="prompt"></p></center>
<textarea id="userInput" name="TypeBox" rows="4" cols="100" autofocus></textarea>
</div>
</div>
</body>
</html>
// THIS IS THE JAVASCRIPT CODE
let scoreTime;
var seconds = 0;
var minutes = 0;
let score = 0;
const userInput = document.getElementById("userInput");
const promptBox = document.getElementById("prompt");
const outcomeText = document.getElementById("outcome");
const bossHealthtText = document.getElementById("bossHealth");
const timer = document.getElementById("time");
const bossSprite = document.getElementById("bossSprite");
const secondsText = document.getElementById("seconds");
const minutesText = document.getElementById("minutes");
let gameActive = true;
document.addEventListener('keypress', function(event){
if (event.key === 'Enter'){
checkInput();
}
});
let bossHealth = 100;
let multiplier = 10;
let mistakes = 0;
//
const prompts = ["How much wood could a woodchuck chuck if a woodchuck could chuck wood?", "I will not lose another pilot.", "I can't find my keys!", "Live as if you were to die tomorrow.", "Toto, I've got a feeling we're not in Kansas anymore...", "May the force be with you.", "If our lives are already written, it would take a courageous man to change the script.", "An apple a day keeps the doctor away.", "Frankly, my dear, I don't give a damn.", "Hello, world!", "My favorite sport is basketball!", "Two things are infinite: the universe and human stupidity; and I'm not sure about the universe.", "You only live once, but if you do it right, once is enough.", "I'm the fastest typer in the wild west!", "Frosty the snowman!", "I'm not a big fan of ice cream.", "If birds can fly, then we should too.", "I don't like trucks, they look weird.", "I love typing!", "I'm a rocket man, burning on a fuse out there alone.", "The water was blue and the skies the same, it was summer."];
//GAME INIT
bossHealthtText.innerHTML = `BOSS HEALTH: ${bossHealth}`;
function getNewPrompt() {
promptChoice = Math.floor(Math.random() * prompts.length);
let previousPrompt = prompts[promptChoice];
if (previousPrompt === prompts[promptChoice]){
promptChoice = Math.floor(Math.random() * prompts.length);
console.log("COPY OFF");
}
promptBox.innerHTML = prompts[promptChoice];
}
function checkInput(){
if (userInput.value.trim() === promptBox.innerHTML.trim()){
outcome.innerHTML = "Correct";
bossHealth -= 10;
bossHealthtText.innerHTML = `BOSS HEALTH: ${bossHealth}`;
let hitSprite = Math.floor(Math.random() *2);
if(hitSprite === 0){
bossSprite.src = "../imgs/bosshit/bosshit1.png";
}
if(hitSprite === 1){
bossSprite.src = "../imgs/bosshit/bosshit2.png";
}
setTimeout(function(){
bossSprite.src = "../imgs/boss.png";
}, 1000);
if (bossHealth <= 0){
console.log("WORKING");
window.location.href = "./score.html";
createScore();
}
getNewPrompt();
userInput.value = null;
}
else{
outcome.innerHTML = "Try again...";
userInput.value = null;
multiplier --;
mistakes ++;
return;
}
}
function gameTimer(){
console.log("working");
setTimeout(function(){
setInterval(function(){
seconds++;
if(seconds === 60){
minutes ++;
seconds = 0;
}
if (seconds < 9){
secondsText.innerHTML = "0" + seconds;
}
if (seconds > 9){
secondsText.innerHTML = seconds;
}
if(minutes < 9){
minutesText.innerHTML = minutes;
}
if(minutes > 9){
minutesText.innerHTML = minutes;
}
if (seconds < 9){
scoreTime = minutes + ":" + "0" + seconds;
}
if (seconds > 9){
scoreTime = minutes + ":" + seconds;
}
timePoints = minutes + seconds * 2;
return scoreTime;
return timePoints;
}, 1000)
}, 1000);
}
function game(){
gameTimer();
getNewPrompt();
createHeart();
}
function createScore(){
let bonus = Math.floor(Math.random() * 500);
score = timePoints * multiplier + bonus;
export { score };
}
game();
<!-- THIS IS THE SCORE HTML PAGE -->
<!DOCTYPE html>
<!DOCTYPE html>
<html onclick="celebrate()">
<head>
<meta charset="utf-8">
<title>Typeboss || Your Score!</title>
<link rel="stylesheet" href="../css/scorestyle.css">
<style>
#import url('https://fonts.googleapis.com/css2?family=Cabin:wght#500&display=swap');
</style>
</head>
<body>
<center><h1 style="color: whitesmoke;" id="header">YOU BEAT THE BOSS!</h1></center>
<center><p>(CLICK FOR VICTORY MUSIC)</p></center>
<h3 id="time">TIME:</h3>
<p id="playertime"></p>
<h3 id="score">SCORE:</h3>
<p id="playertime"></p>
<h3 id="mistakes">MISTAKES:</h3>
<p id="playertime"></p>
<h2 id="highscore"></h2>
<button id="redirect">BACK TO HOME</button>
</body>
<script type="module" src="../js/gamescript.js" defer></script>
</html>
// AND HERE IS THE SCORE'S CODE
winMusic = new Audio();
winMusic.src = "./winmusic.mp3";
function celebrate(){
winMusic.play();
winMusic.loop = tru
}
import { score } from "./gamescript.js";
const scoreText = document.getElementById("score");
scoreText.innerHTML = score + " points!"
I hope I can get this issue resolved, and I hope this post was clear enough to understand. This is my first post on stack so please do let me know if I formatted it wrong, and any feedback that could make it easier to understand in the future. Thank you in advance and have a good day.

use cookie for saving variables!
function setCookie(cname, cvalue, exdays) {
const d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
let expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
let name = cname + "=";
let ca = document.cookie.split(';');
for(let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
let user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
setCookie("username", user, 365);
}
}
}

You can use Session Storage or for this.

Related

How to correct my wpm formula in JavaScript?

I am a learning student, Currently I am working on a typing website. I am using codingartist code as base. I have done some modification in this code. At the time variable I am taking value from user with the help of select option menu, so this is my time variable :
let time = parseInt(document.getElementById("time-select").value);
This is my html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Typing Test</title>
<!-- Google Fonts -->
<link
href="https://fonts.googleapis.com/css2?family=Poppins:wght#400;600&display=swap"
rel="stylesheet"
/>
<!-- Stylesheet -->
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<div class="select">
<label for="time-select">Select time:</label>
<select id="time-select">
<option value="60">1 minute</option>
<option value="90" selected>1.5 minutes</option>
<option value="120">2 minutes</option>
<option value="300">5 minutes</option>
<option value="480">8 minutes</option>
<option value="600" >10 minutes</option>
</select>
</div>
<div class="stats">
<p>Time: <span id="timer">0s</span></p>
<p>Mistakes: <span id="mistakes">0</span></p>
</div>
<div
id="quote"
onmousedown="return false"
onselectstart="return false"
></div>
<textarea
rows="3"
id="quote-input"
placeholder="Type here when the test starts.."
></textarea>
<button id="start-test" onclick="startTest()">Start Test</button>
<button id="stop-test" onclick="displayResult()">Stop Test</button>
<div class="result">
<h3>Result</h3>
<div class="wrapper">
<p>Accuracy: <span id="accuracy"></span></p>
<p>Speed: <span id="wpm"></span></p>
</div>
</div>
</div>
<!-- Script -->
<script src="script.js"></script>
</body>
</html>
This is my index.js
//Random Quotes Api URL
const quoteApiUrl = "https://api.quotable.io/random?minLength=80&maxLength=100";
const quoteSection = document.getElementById("quote");
const userInput = document.getElementById("quote-input");
let quote = "";
let time = parseInt(document.getElementById("time-select").value);
let timer = "";
let mistakes = 0;
function updateTime() {
// Get the new time value from the dropdown menu
let time = parseInt(document.getElementById("time-select").value);
// Update the timer display
document.getElementById("timer").innerText = time + "s";
}
// Add an event listener to the dropdown menu to call the updateTime function when the value changes
document.getElementById("time-select").addEventListener("change", updateTime);
//Display random quotes
const renderNewQuote = async () => {
//Fetch contents from url
const response = await fetch(quoteApiUrl);
//Store response
let data = await response.json();
//Access quote
quote = data.content;
//Array of characters in the quote
let arr = quote.split("").map((value) => {
//wrap the characters in a span tag
return "<span class='quote-chars'>" + value + "</span>";
});
//join array for displaying
quoteSection.innerHTML += arr.join("");
};
//Logic for comparing input words with quote
userInput.addEventListener("input", () => {
let quoteChars = document.querySelectorAll(".quote-chars");
//Create an arrat from received span tags
quoteChars = Array.from(quoteChars);
//array of user input characters
let userInputChars = userInput.value.split("");
//loop through each character in quote
quoteChars.forEach((char, index) => {
//Check if char(quote character) = userInputChars[index](input character)
if (char.innerText == userInputChars[index]) {
char.classList.add("success");
}
//If user hasn't entered anything or backspaced
else if (userInputChars[index] == null) {
//Remove class if any
if (char.classList.contains("success")) {
char.classList.remove("success");
} else {
char.classList.remove("fail");
}
}
//If user enter wrong character
else {
//Checks if we alreasy have added fail class
if (!char.classList.contains("fail")) {
//increment and display mistakes
mistakes += 1;
char.classList.add("fail");
}
document.getElementById("mistakes").innerText = mistakes;
}
//Returns true if all the characters are entered correctly
let check = quoteChars.every((element) => {
return element.classList.contains("success");
});
//End test if all characters are correct
if (check) {
displayResult();
}
});
});
//Update Timer on screen
function updateTimer() {
if (time == 0) {
//End test if timer reaches 0
displayResult();
} else {
document.getElementById("timer").innerText = --time + "s";
}
}
//Sets timer
const timeReduce = () => {
time = parseInt(time);
timer = setInterval(updateTimer, 1000);
};
//End Test
const displayResult = () => {
//display result div
document.querySelector(".result").style.display = "block";
clearInterval(timer);
document.getElementById("stop-test").style.display = "none";
userInput.disabled = true;
let timeTaken = 1;
if (time != 0) {
timeTaken = (60 - time) / 60;
}
document.getElementById("wpm").innerText =
(userInput.value.length / 5 / timeTaken).toFixed(2) + " wpm";
document.getElementById("accuracy").innerText =
Math.round(
((userInput.value.length - mistakes) / userInput.value.length) * 100
) + " %";
};
//Start Test
const startTest = () => {
mistakes = 0;
timer = "";
userInput.disabled = false;
timeReduce();
document.getElementById("start-test").style.display = "none";
document.getElementById("stop-test").style.display = "block";
};
window.onload = () => {
userInput.value = "";
document.getElementById("start-test").style.display = "block";
document.getElementById("stop-test").style.display = "none";
userInput.disabled = true;
renderNewQuote();
};
I am trying to create a typing test that measures the words per minute (WPM) of the user's input. However, the WPM calculation is not giving the correct results. When I test the code, the WPM value is always much higher or as same as word typed (even if i take 2min. for typing) than expected.
let timeTaken = 1;
if (time != 0) {
timeTaken = (60 - time) / 60;
}
document.getElementById("wpm").innerText =
(userInput.value.length / 5 / timeTaken).toFixed(2) + " wpm";
I know given code is wrong with 60 default value. so i tried this:
let remainTime = time - parseInt(timer);
let timeTaken = time - remainTime;
but it also gives doesn't give correct wpm value.
Try this I am sure that it will work as per my research:
let timerLengthInput = document.getElementById("time-select");
const timerLength = timerLengthInput.value;
let time = timerLength;
and write the in your displayResult-
let timeTaken = 1;
if (time !== 0) {
timeTaken = (timerLength - time) / 60;
}
document.getElementById("wpm").innerText =
(userInput.value.length / 5 / timeTaken).toFixed(2) + " wpm";
timeReduce function-
const timeReduce = () => {
timer = setInterval(updateTimer, 1000);
};

how to make to stop on specific number when button clicked

<html>
<head>
<style>
</style>
</head>
<body>
<label id="minutes">0</label>
<label id="seconds">0</label>
<script type="text/javascript">
var secondsLabel = document.getElementById("seconds");
var totalSeconds = 0;
setInterval(setTime, 150);
function setTime()
{
++totalSeconds;
secondsLabel.innerHTML = pad(totalSeconds%10);
}
function pad(val)
{
var valString = val + "";
if(valString.length < 1)
{
return "0" + valString;
}
else
{
return valString;
}
}
</script>
<script type="text/javascript">
var minutesLabel = document.getElementById("minutes");
var totalSeconds = 0;
setInterval(setTime, 100);
function setTime()
{
minutesLabel.innerHTML = pad(totalSeconds%6);
}
function pad(val)
{
var valString = val + "";
if(valString.length < 1)
{
return "0" + valString;
}
else
{
return valString;
}
}
</script>
<script>
function myFunction1() {
var a = document.getElementById("minutes");
var b = document.getElementById("seconds");
dont' know what should i write in here
</script>
<button onclick="myFuntion1">click</button>
</body>
<html>
i wanna make stop button in specific number.
so whenever you clicked the button
the countup stop on 15.
any help will be so appreciated. :)
thanks
--repeat cause it said i can't upload this question because of not enough detail.
i wanna make stop button in specific number.
so whenever you clicked the button
the countup stop on 15.
any help will be so appreciated. :)
thanks
Print out the 1 and 5.
Stop the timer. (You should assign a variable to each timer first)
<html>
<head>
<style>
</style>
</head>
<body>
<label id="minutes">0</label>
<label id="seconds">0</label>
<script type="text/javascript">
var secondsLabel = document.getElementById("seconds");
var totalSeconds = 0;
var t1 = setInterval(setTime, 150);
function setTime()
{
++totalSeconds;
secondsLabel.innerHTML = pad(totalSeconds%10);
}
function pad(val)
{
var valString = val + "";
if(valString.length < 1)
{
return "0" + valString;
}
else
{
return valString;
}
}
</script>
<script type="text/javascript">
var minutesLabel = document.getElementById("minutes");
var totalSeconds = 0;
var t2 = setInterval(setTime, 100);
function setTime()
{
minutesLabel.innerHTML = pad(totalSeconds%6);
}
function pad(val)
{
var valString = val + "";
if(valString.length < 1)
{
return "0" + valString;
}
else
{
return valString;
}
}
</script>
<script>
function myFunction1() {
document.getElementById("minutes").innerHTML = '1';
document.getElementById("seconds").innerHTML = '5';
clearInterval(t1);
clearInterval(t2);
}
</script>
<button onclick="myFunction1()">click</button>
</body>
<html>

Show div only once per user session? [duplicate]

This question already has answers here:
Show welcome div only once per user / browser session
(3 answers)
Closed 6 years ago.
How would it be done with this? I have jQuery if that would help.
<div id="RLAD-wrapper">
<div id="RLAD">
<p>stuff</p>
</div>
</div>
if(localStorage.getItem("iknowyou")) {
document.body.innerHTML = "You were already here";
} else {
document.body.innerHTML = "Oh. A new guest...";
localStorage.setItem("iknowyou", "true");
}
This utilizes localStorage to store a persistent state across sessions.
You could also do it with cookies:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div class="mydiv" style="display: none;">
this is a div
</div>
<script
src="https://code.jquery.com/jquery-3.1.1.slim.min.js"
integrity="sha256-/SIrNqv8h6QGKDuNoLGA4iret+kyesCkHGzVUUV0shc="
crossorigin="anonymous"></script>
<script>
$(function() {
// Cookies
function setCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
// Validate cookie
var myCookie = getCookie("MyCookie");
if (myCookie == null) {
// alert('No cookei');
$('.mydiv').css('display','block');
setCookie("MyCookie", "foo", 7);
}
else {
// alert('yes cookei');
$('.mydiv').css('display','none');
}
});
</script>
</body>
</html>
The code below sets an item in localStorage to Date.now, and checks if it is past 3 days. The setting of the item is in an else statement to prevent the user from getting their time reset every single time they run the website.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Put anything you want here</title>
</head>
<body>
<div id="aDiv">
Div content
</div>
<script>
if(Date.now() - parseInt(localStorage.getItem("pageVisitedTime").getTime(), 10) < 2.592e+8){
document.getElementById("aDiv").style.display = "none";
}
else{
localStorage.setItem("pageVisitedTime", "" + Date.now());
}
</script>
</body>
</html>

JavaScript - Calling a function again is not working

This is kind of hard to explain, but I want to make it so when someone gets the answer right to a question, they get a new question. I have tried calling the function more than once but that doesn't work. I have tried many things like making cookies, but I can't get it to work. Here is my current code:
//Getting elements
var ques = document.getElementById("question");
var ansBox = document.getElementById("ansBox");
var submitBtn = document.getElementById("submitBtn");
var isCorrect = document.getElementById("isCorrect");
var quesNum = document.getElementById("quesNum");
//Variables
var num1 = Math.floor((Math.random() * 10) + 1);
var num2 = Math.floor((Math.random() * 10) + 1);
var ans = num1 + num2;
var questionNumber = 1;
quesNum.innerHTML = questionNumber;
//Check if answer is correct or not
function checkAns() {
if(ansBox.value == ans) {
isCorrect.innerHTML = "Good job! Your answer was correct!";
questionNumber++;
quesNum.innerHTML = questionNumber;
ques.innerHTML = " ";
question();
//Call if statement when questionNumber = 10 and disable submitBtn and ansBox
if(questionNumber == 10) {
isCorrect.innerHTML = "Congratulations! You have completed all 10 questions! Refresh the page to do more!";
ansBox.disabled = true;
submitBtn.disabled = true;
}
} else {
isCorrect.innerHTML = "Uh-oh, your answer was incorrect!";
}
}
//Ask question
function question() {
ques.innerHTML = num1 + " + " + num2;
}
//Call question function
question();
body {
font-family: Arial;
}
div {
padding-top: 50px;
text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div>
<h1>Edu Game One</h1>
<h3 id="question"></h3>
<input type="text" id="ansBox" />
<button id="submitBtn" type="submit" onclick="checkAns()">Submit</button>
<p id="isCorrect"></p>
<span id="quesNum"></span>
<span>/ 10</span>
</div>
<script src="scripts.js"></script>
</body>
</html>
The code that generates the two random numbers is currently not inside a function, so it runs once when the page first loads. You just need to move those lines inside your question() function, so then each time question() is called you'll get new random values.
You'll want to set the ans value from there too (but leave ans as a global variable so that it can be checked from your other function):
function question() {
var num1 = Math.floor((Math.random() * 10) + 1);
var num2 = Math.floor((Math.random() * 10) + 1);
ans = num1 + num2;
ques.innerHTML = num1 + " + " + num2;
}
In context:
//Getting elements
var ques = document.getElementById("question");
var ansBox = document.getElementById("ansBox");
var submitBtn = document.getElementById("submitBtn");
var isCorrect = document.getElementById("isCorrect");
var quesNum = document.getElementById("quesNum");
//Variables
var ans;
var questionNumber = 1;
quesNum.innerHTML = questionNumber;
//Check if answer is correct or not
function checkAns() {
if(ansBox.value == ans) {
isCorrect.innerHTML = "Good job! Your answer was correct!";
questionNumber++;
quesNum.innerHTML = questionNumber;
ques.innerHTML = " ";
question();
//Call if statement when questionNumber = 10 and disable submitBtn and ansBox
if(questionNumber == 10) {
isCorrect.innerHTML = "Congratulations! You have completed all 10 questions! Refresh the page to do more!";
ansBox.disabled = true;
submitBtn.disabled = true;
}
} else {
isCorrect.innerHTML = "Uh-oh, your answer was incorrect!";
}
}
//Ask question
function question() {
var num1 = Math.floor((Math.random() * 10) + 1);
var num2 = Math.floor((Math.random() * 10) + 1);
ans = num1 + num2;
ques.innerHTML = num1 + " + " + num2;
}
//Call question function
question();
body {
font-family: Arial;
}
div {
padding-top: 50px;
text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div>
<h1>Edu Game One</h1>
<h3 id="question"></h3>
<input type="text" id="ansBox" />
<button id="submitBtn" type="submit" onclick="checkAns()">Submit</button>
<p id="isCorrect"></p>
<span id="quesNum"></span>
<span>/ 10</span>
</div>
<script src="scripts.js"></script>
</body>
</html>
Also, you may want to move the following lines:
questionNumber++;
quesNum.innerHTML = questionNumber;
...to be before the if statement, because at the moment it doesn't count questions attempted, it counts only questions that were answered correctly.

page refresh countdown timer does not continue using javascript

<html>
<head>
<script>
var seconds=3600;
function secondPassed() {
var minutes = Math.round((seconds-30)/60);
console.log(minutes);
var hours=Math.round((minutes)/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML =hours + ":"+ minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(myVar);
document.getElementById('countdown').innerHTML = "Time Out";
} else {
seconds--;
}
}
var myVar = setInterval(secondPassed ,1000);
</script>
</head>
<body>
<p id="countdown"></p>
</body>
</html>
MY Question : page refresh and countdown timer does not continue.
You can do this by using javascript cookies only but you need to use two file
first file contains total time you need for countdown i.e in your code is 3600 seconds
let us take first file index.html write code
<!DOCTYPE html>
<html>
<head>
<title>Countdown timer</title>
<script type="text/javascript">
var seconds = 3600;
document.cookie = "timer=" + seconds;
window.location.href = "time.html";
</script>
</head>
<body>
</body>
</html>
Next second file let us take time.html add below code
<html>
<head>
<script>
function getCookie(name) {
var nameEQ = name + "=";
//alert(document.cookie);
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(nameEQ) != -1) return c.substring(nameEQ.length,c.length);
}
return null;
}
// var seconds=7200;
// document.cookie = "timer=" + seconds;
function secondPassed() {
seconds = parseInt(getCookie('timer'));
console.log(seconds);
var minutes = parseInt(seconds / 60, 10);
console.log(minutes);
var remainingSeconds = parseInt(seconds % 60, 10);
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds + ' minutes remaning';
if (seconds == 0) {
clearInterval(myVar);
document.getElementById('countdown').innerHTML = "Time Out";
} else {
seconds--;
}
document.cookie = "timer=" + (seconds);
}
var myVar = setInterval(secondPassed ,1000);
</script>
</head>
<body>
<p id="countdown"></p>
</body>
</html>
Note : whenever you want to run countdown timer just run time.html, even if you refresh also, time remains same
Note : if you want to refresh page or want to add when time up add your activity in
if (seconds == 0) {
clearInterval(myVar);
// add activity
}

Categories

Resources