The code to set 30 second timer - javascript

Please, I am trying to link all my pages with progressive 30 seconds count timer using JavaScript and html without being recount on page navigation. Thanks!

With more information in mind from comments, here's your code:
Somewhere in index.html
<div id="counter"></div>
YourScript.js
// Simplifies getting the value of a cookie
function getCookie(name)
{
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
}
// Max time for cookie
var count = 30;
if(document.cookie && document.cookie.match('counter')) {
// Set value of counter to match the cookie
count = getCookie('counter');
}
// Runs once per second
setInterval(function() {
// Decrease the value of count by 1 every second
count--;
// if count is less or equal to 0 we move to menu.html
if(count <= 0) {
window.location.href="menu.html"
}
// Set the text inside the <div id="counter"></div> to the value of counter
document.getElementById('counter').innerHTML = count;
// Set the value of the cookie to match the value of our counter variable
document.cookie = 'counter=' + count;
}, 1000);
I created a jsfiddle for this but for some reason jsfiddle doesn't want to create a unique URL for me right now... Go to jsfiddle.net and copy paste this into the script field, and the div into the html area, then press Run several times and you'll see that the counter keeps counting down, persisting between page refreshes.

Related

Adding a reset button to a Javascript HTML game?

I am second semester, taking a class in Javascript. Basically, we were given the HTML and CSS for a website, and it is supposed to do the following:
It's a number game. The computer generates a number, and you have ten tries to guess this number. If you get to zero, the computer wins, and there is a reset button which should reset all the variables and start again. Only problem is, I cannot for the life of me figure out how to reset the countDown variable after the score reaches 0. Please help. Also we are using only pure Javascript for this course for now. I don't want to cheat, I am more trying to figure out what the issue is that's holding me back.
var countDown = 10;
var computerNumber = Math.floor((Math.random() * 501) + 1);
function generate() {
playerNumber = document.getElementById("guess").value;
if (computerNumber == playerNumber && countDown > 0) {
alert("Congratulations! You've won!");
} else if (playerNumber < computerNumber && countDown > 0) {
countDown--;
document.getElementById("guesses").value = countDown;
document.getElementById("result").value = "Too Low";
} else if (playerNumber > computerNumber && countDown > 0) {
countDown--;
document.getElementById("guesses").value = countDown;
document.getElementById("result").value = "Too High";
} else if (countDown == 0) {
alert("Game Over. The Number Was " + computerNumber);
}
}
function reset() {
countDown = 10;
computerNumber = Math.floor((Math.random() * 501) + 1);
}
In the reset function, you would need to update the element that displays the countDown in the HTML
Here you need to add the reset button in the html:
<input type="button" class="reset-button" value="Reset Count">
Then grab that button in your JS below the reset function and attach an eventListener that fires the reset function when clicked:
const resetBtn = document.querySelector('.reset-button')
resetBtn.addEventListener('click', reset )
And that's it.
You would probably want the count displayed on the page, too. You could add a line in the reset function that pushes the new value of countDown into the html (with element.textContent = countDown.toString(), for example)
If you take a JS class in 2021 you should definitely use const and let instead of var, and let your teacher know why. Using var works, though, but will show a future employer that you're out of touch with what's going on in the JS world.

Fire javascript every x page load, for example, every 3rd page

I'm sure this question has been answered, before, but my searches are coming up empty.
I have a simple jQuery function (that slides in a box after the page has been scrolled down). It works fine.
However, how do I set cookies, or other method, to make it execute on the first page load and, then, on every 3rd page load of the session, after that?
A little snippet like this should work for you.
(function () {
// Get the countdown from localStorage
var countdown = Number(window.localStorage.getItem('countdown'));
// If countdown isn’t set it or if it has
// run a couple times it’ll be `0`
// Either way—we reset countdown and run the function
if (!countdown) {
countdown = 3;
// Run the function
}
// Update the countdown
window.localStorage.setItem('countdown', countdown - 1);
})();
These are both very instructive answers (my javascript skill is at the piece-it-together level). If it's helpful to someone, even though the question was for a javascript solution, I realized there might be a PHP solution, as well.
This worked, too:
<?php //Slide-in ad will show every x pages
$slide_ad_frequency=3;
session_start();
//increase the already-set counter by 1 or initiate the counter with a value of 1
if( isset( $_SESSION['counter'] ) )
{
$_SESSION['counter'] += 1;
}
else
{
$_SESSION['counter'] = 1;
}
//If counter equals the ad frequency setting
if($_SESSION['counter'] % $slide_ad_frequency == 0) : ?>
... Code to execute ...
<?php endif ?>
You can store the count of window loads on the sessionStorage so that data won't be lost on every reload. The data will be cleared when the tab is closed. If you want your data to not expire when the session ends, you should instead use localStorage; both have the same implementation.
window.onload = doSomething;
function doSomething() {
let count = sessionStorage.getItem('noOfPageLoads');
if( count ) { //if count is not null, increment it
count++;
sessionStorage.setItem('noOfPageLoads', count); //update the local storage
}
else { //if count is null, it's the first load, so put it in the local storage
count = 0;
sessionStorage.setItem('noOfPageLoads', count);
}
console.log('noOfPageLoads = '+ count)
if( count===0 || count===3 ) {
console.log('do something now');
//do what you want here
}
}

JS Browser with pause function, help please

I wrote this program in js that goes through a list of URLs, where it stays on each page for a few seconds, closes the current window, and open the next in line. Everything works perfect, now I need it to stop/pause every 5 links. The second part of this project would be to create my own browser that open up like a program and there would be three buttons (start, continue, stop, maybe pause as well). I'd like start button to obviously start the function which goes through the pages, continue would be when it pauses on the fifth link I'd like a pop up message to say "wake up" and have the option to click "ok" only. Then you would have to click on continue in order for the function to continue. Stop would stop the function no matter where it has reached in the list. I'd like the links to show up in my browser not in Google Chrome or any other. What program should I use to design the browser? Here is the code of the current program:
var urlList = ['www.youtube.com',
'www.google.com',
'www.bing.com',
'www.yahoo.com',
'www.facebook,com',
'www.windows.com',
'www.opera.com',];
var wnd;
var curIndex = 0; // a var to hold the current index of the current url
function openWindow(){
wnd = window.open(urlList[curIndex], '', '');
if (curIndex % 5 == 0) {
}
setTimeout(function () {
wnd.close(); //close current window
curIndex++; //increment the index
if(curIndex < urlList.length) openWindow(); //open the next window if the array isn't at the end
}, 4000);
}
openWindow();
Help me finish the if statement...
Add a variable for your timeout period, instead of using the value 4000. Note that it must have global scope. I've added a variable calleddelay here:
var wnd;
var curIndex = 0; // a var to hold the current index of the current url
var delay;
Then, use the new variable in your openWindow() function, setting its value to a longer period in your if statement when you want the pauses to happen.
I've used a ternary operator here for instead of an if statement, but you could use an if statement just as well:
function openWindow(){
wnd = window.open('http://' + urlList[curIndex], '', '');
// pause for 30 seconds instead of 4 if the condition is met
delay = (curIndex > 0 && curIndex % 3 == 0 ? 30000 : 4000)
setTimeout(function () {
wnd.close(); //close current window
curIndex++; //increment the index
if(curIndex < urlList.length) openWindow(); //open the next window if the array isn't at the end
}, delay);
}

setTimeout executes itself right away/on clear

I'm making a webpage where user events are logged in.
To test the feature I made a small, independant webpage with a teaxtarea and a text input. The events logged are those performed on the input element.
I want to prevent the same event text to be shown multiple times in a row, but I can't seem to prevent them from showing up!
I also want to add a line to separate event groups 0.5 seconds after no other event happened, but the line seems to appear on every event trigger, evenif I use clearTimeout with the timeout ID.
Basically: I don't want any line to be repeated. If the last line is a separator line, then it must not add another one. Yet it doesn't see to work.
JSFiddle Demo
Here is my code:
JavaScript
var timerID = 0;
function addSeparateLine()
{
document.getElementById('listeEvenements').value += "--------------------\n";
}
function show(newEventText)
{
var eventListField = document.getElementById('listeEvenements');
var eventList = [];
if (eventListField.value.length > 0)
{
eventList = eventListField.value.split("\n");
}
var eventCounter = eventList.length;
if (eventList[eventCounter - 2] == newEventText)
{
clearTimeout(timerID);
newEventText = "";
}
timerID = setTimeout(addSeparateLine, 500);
if (newEventText !== "")
{
eventListField.value += newEventText + "\n";
}
return true;
}
HTML
<fieldset id="conteneurLogEvenements">
<legend>Events called from HTML attribute</legend>
<textarea id="listeEvenements" rows="25"></textarea>
<input id="controleEcoute" type="text" onBlur="show('Blur');" onchange="show('Change');" onclick="show('Click');" onfocus="show('Focus');" onMousedown="show('MouseDown');" onMousemove="show('MouseMove');" onMouseover="show('MouseOver');" onkeydown="show('KeyDown');"
onkeypress="show('KeyPress');" onkeyup="show('KeyUp');" />
</fieldset>
http://jsfiddle.net/z6kb4/2/
It sounds like what you want is a line that prints after 500 milliseconds of inactivity, but what your code currently says to do is "print a line 500 milliseconds after any action, unless it gets canceled". You can get better results by structuring the code more closely to your intended goal.
Specifically, instead of scheduling a new timeout every time an event occurs, simply start a loop when the first event occurs that checks the time that has elapsed since the most recent event received and then prints a line when the elapsed time exceeds the desired threshold (500 milliseconds). Something like:
function addSeparateLine() {
var elapsed = new Date().getTime() - lastEventTime;
if (elapsed >= 500) {
document.getElementById('listeEvenements').value += "--------------------\n";
clearInterval(timerID);
timerID = -1;
}
}
...and then you schedule it like:
if(newEventText !== "") {
lastEventTime = new Date().getTime();
eventListField.value += newEventText+"\n";
if (timerID == -1) {
timerID = setInterval(addSeparateLine,100);
}
}
Working example here: http://jsfiddle.net/z6kb4/4/
Because you are not actually stopping the show function in any way. The clearTimeout only applies to the separator add. I have updated your fiddle. You need to wrap your function with
if (+new Date() - lastfire < 500) return;
and
lastfire = +new Date();
(before the last return--see the updated fiddle). Also, make sure to stick the global definition var lastfire = -1; somewhere up top.

How to run a timer continually? (Do not start from the beginning, when yo do refresh)

I have my code of timer that only alert when minutes and seconds are 0:
status = false;
hour_to_start = some_value; // THIS VALUE IS PUT FOR OTHER PERSON
min = 15; //THIS VALUE IS PUT FOR ANOTHER PERSON
seg = 60;
function timecamisa(){
if (seg > 0){
seg--;
}else{
if(seg==0){
min--;
seg=60;
}
}
if(min == 0 && seg==0){
// END - STOP ALL
min= 0;
seg = 0;
status = true;
}
var timer = min + ' minutos ' + seg + ' segundos';
document.getElementById("times-get").innerHTML = timer;
if(status != true){
setTimeout("timecamisa()",1000)//This reload this function (timecamisa())
}else{
alert("END!");
}
In my HTML i have a <span id="times-get"> where print the timer.
BUT, when i press F5 my timer return to the beginning and does not continue where you left off... So, How to do this? Anyone have a example?
My target is that my timer work with my variable 'hour_to_start' and 'min' where.. This timer displays the countdown from my variable 'hour_to_start' in 'x' 'min' (my other variable). And when the variable MIN is 0(ie, complete the mins).. Alert anything.
UPDATE!
OK, i do it with Jquery Plugin countdown Timer.. Is very useful for more than 1 timers.
Now, mi problem is.. when i change the time of my computer, this timer change too.
How to avoid changing my timer when you change the time, date and / or time of my machine?
You will need to get the time from either your server or from some remote server (e.g. via a javascript from someone else's server). If you get the time using javascript it will always depend on the clock of the user's machine.

Categories