Javascript auto page refresh code - javascript

this is the code that comes in head section and it will automatically refresh the whole page in 1 min as i put 6000 in the code below
<script type="text/javascript">
setTimeout('window.location.href=window.location.href;', 6000);
</script>
is there any way for example, when there's 10 seconds left to refresh the page then, a button will display and say "Click here to reset timer" and it will reset that timer to 1 min again?

<script language="javascript">
var timeout,interval
var threshold = 15000;
var secondsleft=threshold;
startschedule();
window.onload = function()
{
startschedule();
}
function startChecking()
{
secondsleft-=1000;
if(secondsleft <= 10000)
{
document.getElementById("clickme").style.display="";
document.getElementById("timercounter").innerHTML = Math.abs((secondsleft/1000))+" secs";
}
}
function startschedule()
{
clearInterval(timeout);
clearInterval(interval);
timeout = setTimeout('window.location.href=window.location.href;', threshold);
secondsleft=threshold;
interval = setInterval(function()
{
startChecking();
},1000)
}
function resetTimer()
{
startschedule();
document.getElementById("clickme").style.display="none";
document.getElementById("timercounter").innerHTML="";
}
</script>
Please wait...<span id="timercounter"></span>
<button id="clickme" style="display:none;" onclick="javascript:resetTimer();">Click here to reset timer</button>

Assuming you have the following html for the button:
<button id="cancel-reload-button" style="display: none" onclick="cancelReload()">Cancel Reload</button>
And this as the script (Note: this gives the idea, but is not neccesarily fully tested):
// Variable for holding the reference to the current timeout
var myTimeout;
// Starts the reload, called when the page is loaded.
function startReload() {
myTimeout = setTimeout(function() {
document.getElementByID("cancel-reload-button").style.display = "inline";
myTimeout = setTimeout(function() {
window.location.reload();
} 10000)
}, 50000);
}
// Cancel the reload and start it over. Called when the button is
// clicked.
function cancelReload() {
clearTimeout(myTimeout)
startReload()
}
// On page load call this function top begin.
startReload();
I created two functions, one for starting the reload and the second one for cancelling it.
Then I assigned the timeout to the variable myTimeout which can be used to later cancel the timeout.
Then I called myTimeout twice - Once for 50 secs, at which point it shows the button and once for 10 secs after which it finally reloads.

How about below? If you click on OK to reset timer, it would keep giving the confirm box every 50 seconds. If you click cancel, it will refresh the page in 10 seconds.
setInterval(function(){ var r = confirm("Reset Timer");
if (r == true) {
setTimeout('window.location.href=window.location.href;', 60000);
} else {
setTimeout('window.location.href=window.location.href;', 10000);
}
}, 50000);
Note: In your question you specified 1 minute, but your code works for 6 seconds(6000 -- > 6 seconds not 60 seconds) I have included for a minute

You can use 2 setTimeout calls, one to make the "Reset" button show up and another one for the refresh timer reset. The trick is to store the second setTimeout on a global variable and use clearTimeout to reset it if the button is pressed.
Here is some JavaScript code to illustrate:
<script type="text/javascript">
var autoRefreshTime = 30 * 1000; // 60000ms = 60secs = 1 min
var warningTime = autoRefreshTime - (10 * 1000); // 10 secs before autoRefreshTime
waitTimeout = setTimeout('window.location.href=window.location.href;', autoRefreshTime);
warningTimeout = setTimeout('ShowResetButton();', warningTime);
function ShowResetButton() {
// Code to make the "Reset" button show up
}
// Make this function your button's onClick handler
function ResetAutoRefreshTimer() {
clearTimeout(waitTimeout);
waitTimeout = setTimeout('window.location.href=window.location.href;', autoRefreshTime);
}
</script>

The way I would do it is make a function with a timeout, and invoke that function
<script type="text/javascript">
var refreshFunc = function(){
setTimeout(function(){
var r = confirm("Do you want to reset the timer?");
if(r === false){
window.location.href=window.location.href;
}else{
refreshFunc();
}
}, 6000);
};
refreshFunc();
</script>
One big problem with using confirm in this case is you cannot program it to reject. You would have to implement you own modal/dialog box so you can auto reject in 10 seconds.

Try using setInterval():
var time;
$(function() {
time = $('#time');
$('#reset').on('click', reset);
start();
});
var timer, left;
var start = function() {
left = +(time.text()); //parsing
timer = setInterval(function() {
if (0 <= left) {
time.text(left--);
} else {
clearInterval(timer);
location.replace(location);
}
}, 1000);
};
var reset = function() {
if (timer) {
clearInterval(timer);
}
time.text('59');
start();
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h1><span id='time'>59</span> second(s) left</h1>
<input id='reset' value='Reset' type='button' />

Related

Javascript or Jquery function with timer that resets each time it is called

I am looking for a way to call a function that should wait for 1000 miliseconds before executing. And when the function is called again before the 1000 miliseconds are reached, the timer should restart. So that the function runs 1000 miliseconds after the last time it was called.
So let's say I have a button:
<button type="button" id="btnclick">Click Me!</button>
And I want to display an alert after exactly 1000 miliseconds after the last time it was clicked. But when the button is clicked a second time, before the 1000 miliseconds have past, then the timer should restart.
If someone clicks the button 1 time, then the alert displays 1 second after the click.
If someone clicks the button, and then clicks again after 999 miliseconds, and then again after again 999 miliseconds, then I want to run the function 1 second after the last click (so 2,98 seconds after the first click).
Is this possible? And how?
My Best guess would be something like:
function delay(callback, ms) {
var timer = 0;
return function () {
var context = this, args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
callback.apply(context, args);
}, ms || 0);
};
}
$('#btnclick').click(function(e){
console.log('I want to see this everytime the button is clicked, without any delay');
delay(waitFunction(),1000);
});
function waitFunction(){
console.log('I want to see this 1 second after the LAST click');
}
(inspiration from: Wait for function till user stops typing )
Yes it is possible. you just have to check if an timeout is already counting down and, if it is, reset it. Here is a simple example.
// set timer-variable
var timer = null;
//on button-click
$('#btnclick').click (function (e) {
//clear timeout if already applied
if (timer) {
clearTimeout (timer);
timer = null;
}
//set new timeout
timer = setTimeout (function () {
//call wait-function and clear timeout
waitFunction ();
clearTimeout (timer);
timer = null;
}, 1000);
});
function waitFunction () {
console.log ('I want to see this 1 second after the LAST click');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="btnclick">Click Me!</button>
I used lastclick variable to store date user clicked.
I defined lastclickworked variable to avoid double setTimeout calls. In settimeout function, i checked if 1 second passed, run the code. if 1 second doesn't passed then call settimeout again with 1 seconds- passed time
var lastclick=null;
var lastclickworked=true;
function clickMe(){
lastclick=new Date();
if(lastclickworked)
runcallback(1000);
}
function runcallback(milliseconds){
lastclickworked=false;
setTimeout(function(){
var current = new Date();
var milliseconds = (current.getTime() - lastclick.getTime());
if(milliseconds<1000){
runcallback(1000-milliseconds);
}else{
lastclickworked=true;
console.log('you clicked 1 second ago');
}
},milliseconds);
}
<button onclick="clickMe();">Click Me!</button>

JavaScript Timeout reset mechanism

What I want:
There are two pictures that are being switched/swapped every three seconds.
I want to make it so that when the button is clicked, the picture switches and the auto-swap resets. So if the button is clicked, the image swaps and three seconds later, it will auto-swap, until the button is clicked again in which the cycle will repeat.
What I have right now
Currently, the problem is that: when the button is clicked, it messes up the timing of the auto-switches.
Edit:
Please don't create a new code base. Just modify mines. The code doesn't have to be an expert super concise level. I'm only three weeks into JavaScript (and it's my first programming language). I have to explain to classmates and it wouldn't be nice the code had elements I don't understand. So sorry for the inconvenience.
Right now I just need the button to correctly stop and restart the time.
<html>
<head>
<script>
let reset = setTimeout(change, 3000);
function change() {
if(document.getElementById("picture").src == "https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&h=350") {
document.getElementById("picture").src = "https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&h=350";
}
else {
document.getElementById("picture").src = "https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&h=350";
}
setTimeout(change, 3000);
}
function fastChange() {
clearTimeout(reset);
if(document.getElementById("picture").src == "https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&h=350") {
document.getElementById("picture").src = "https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&h=350";
}
else {
document.getElementById("picture").src = "https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&h=350";
}
}
</script>
</head>
<body>
<input type="button" onclick="fastChange();">
<img src="https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&h=350" id="picture">
</body>
</html>
The reason why your timer resets is because you are not clearing the timeout.
you need to make a reference to the timeout and then use clearTimeout() on it whne you make the fast change. I don't think it is possible or wise to do that inline the way you have it so you code needs to be refactored
let imgSrc1 = 'https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&h=350'
let imgSrc2 = 'https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&h=350'
let imgElement = document.getElementById('picture');
let timeout;
function change() {
if(imgElement.src === imgSrc1) {
imgElement.src = imgSrc2;
} else {
imgElement.src = imgSrc1;
  }
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(change, 3000);
}
You don't even need the second function fastChange. Now you can sent the onClick listener to change() like this
document.getElementById('whatever you want to click').onCLick = change;
Setting and clearing timeouts in multiple places will work, but I prefer using a "main loop" and a variable to count frames.
Here's an example that uses setInterval and resets a timer variable when the button was clicked:
const url1 = "https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&h=350";
const url2 = "https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&h=350";
function change() {
picture.src = picture.src == url1 ? url2 : url1;
}
var timer = 0;
setInterval(function() {
timer++;
time.textContent = timer;
if (timer === 30) fastChange();
}, 100);
function fastChange() {
change();
timer = 0;
}
picture.src = url1;
swap.onclick = fastChange;
#picture {
height: 70vh
}
<button id="swap">SWAP</button> <span id="time"></span><br>
<img id="picture">
You can do this by calling setTimeout and updating the index as necessary. Just be sure to store the most recent timeout id so that it can be cancelled on reset using clearTimeout.
// store the reference to the <img> that contains the picture
const pic = document.getElementById('picture')
// store a list (array) of the two picture urls
const sources = [
'https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&h=350',
'https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&h=350'
]
// used to store a reference to the interval timer you created.
var lastTimer
// a starting index of the list (i.e. which image we are up to right now)
var index = 1
// this functions swaps the image and sets a timer
function startRotation() {
// update the index to the next one (goes 0-1-0-1->etc)
index = 1 - index
// sets the .src of the image element
pic.src = sources[index]
// starts a 3 second timer to call this same function again
// but also stores a reference to the timer so that it can be cancelled
lastTimer = setTimeout(startRotation, 3000)
}
// this functions resets the timer and restarts the process
function reset() {
// stop the current timer if there is one
if(lastTimer){
clearTimeout(lastTimer)
}
// restart the process
startRotation()
}
// start the swapping process on start
startRotation()
<input type="button" onclick="reset();">
<img id="picture">
NOT HOW YOU CLEARTIMEOUT:
<html>
<head>
<script>
var i;
function change() {
if(document.getElementById("picture").src == "https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&h=350") {
document.getElementById("picture").src = "https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&h=350";
}
else {
document.getElementById("picture").src = "https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&h=350";
}
i = setTimeout(change, 3000);
}
function fastChange() {
clearTimeout(i);
if(document.getElementById("picture").src == "https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&h=350") {
document.getElementById("picture").src = "https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&h=350";
}
else {
document.getElementById("picture").src = "https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&h=350";
}
i = setTimeout(change, 3000);
}
</script>
</head>
<body onload="setTimeout(change, 3000)">
<input type="button" onclick="fastChange();">
<img src="https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&h=350" id="picture">
</body>
</html>

Show reset button after counter reaches zero

I would like to hide and then show the "Reset" button as soon as the counter reaches zero.
Index.html:
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<script type="text/javascript" src="countdown.js"></script>
</head>
<body>
<input type="text" id="timer">
<script type="text/javascript">
timer = new Countdown();
timer.init();
</script>
<button id="reset">Reset</button>
<script type="text/javascript">
$("#reset").click(function(){
//timer = new Countdown();
timer.reset();
});
</script>
</body>
</html>
Please see http://jsfiddle.net/orokusaki/o4ak8wzs/1/ for countdown.js
AWolf's answer is a bit fancier than mine, and they made some good points about your code, but I tried to keep mine simple and tried not to change your original code too much.
Your init() function will now hide the Reset button, and I had the update_target() function show the Reset button when the timer expired.
Fiddle: http://jsfiddle.net/rgutierrez1014/o4ak8wzs/4/
In this jsFiddle you'll find the updated code and how you could add that behaviour.
I've also improved your code a bit. It's easier to write Countdown.prototype = { init: function() {...}, ...} then writing Countdown.prototype.init = function() {...}
I also changed your setInterval to setTimeout and start a new timeout every second. That's easier and you don't need to clear the interval at the end. Also the callback function for your interval seemed a bit strange and that probably won't work.
You could add your click handlers in the init method of your countdown object like this $('#start').click(this.start.bind(this)); the .bind(this) is used to change the context inside the click handler to the currently used object. Then this inside of the handler is your object and you can access everything with this.
To hide the reset button at start I've used the css display: none; and if you are at zero then show the button with $('#reset').fadeIn('slow'); or $('#reset').show(); if you don't want the animation.
Update 13.03.2015
As mentioned in the comments I've improved the code and now I'm using a jQuery Countdown plugin.
Please have a look at the latest version in this jsFiddle.
I think it's much better then the other code.
(function () {
function Countdown() {
this.start_time = "00:30";
this.target_id = "#timer";
//this.name = "timer";
}
Countdown.prototype = {
init: function () {
console.log('init called');
this.reset();
$('#start').click(this.start.bind(this));
$('#reset').click(this.reset.bind(this));
},
reset: function () {
time = this.start_time.split(":");
//this.minutes = parseInt(time[0]);
this.seconds = parseInt(time[1]);
this.update_target();
},
tick: function () {
if (this.seconds > 0) //|| this.minutes > 0)
{
if (this.seconds == 0) {
// this.minutes = this.minutes - 1;
this.seconds = 59
} else {
this.seconds = this.seconds - 1;
}
this.start();
}
else {
// show reset button
$('#reset').fadeIn('slow');
}
this.update_target();
},
start: function() {
console.log('start called');
//setTimeout(this.name + '.tick()', 1000);
setTimeout(this.tick.bind(this), 1000);
},
update_target: function () {
seconds = this.seconds;
if (seconds < 10) seconds = "" + seconds;
$(this.target_id).val(this.seconds);
}
};
var counter = new Countdown();
counter.init();
})();
#reset {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="timer">
<button id="start">Start</button>
<button id="reset">Reset</button>

Javascript Inactivity timer logic

I am trying to implement a inactivity timer using javascript
user should be shown a confirm "You are inactive for 2 min, pls click yes to continue"
If the user does not respond for 1 min the user will be redirected to some page
<script type="text/javascript">
var firstTimer = 0;
var SecondTimer = 0;
function closewindow() {
window.setInterval(ShowAlert, 1000);
}
function ShowAlert()
{
firstTimer++;
SecondTimer++;
if(firstTimer==2)
{
firstTimer=0;
confirm('Do you want to Continue');
}
}
function FinalClose()
{
window.setInterval(ShowFinalAlert, 1000);
}
function ShowFinalAlert()
{
if(SecondTimer==3)
{
window.location.href="http://www.google.com";
}
}
</script>
<body onload="closewindow();FinalClose();">
The problem with the above code is if the user does not respond to the first alert, the second timer is not firing, that is when the overall count is 3 min he should be redirected.
what is wrong with the above code.
I'll take a swing at this one
var idle_timer = 120000; // check every 2 minutes
var kick_timer = 60000; // kick user after 1 minute
var redirect = function(){
window.location = "http://google.com";
};
var idler = function(){
// start the kick timer
var kick_timer = setTimeout(redirect, kick_timer);
// prompt user to click OK
if (confirm("You get the boot in 60 seconds. Do you want the boot?")) {
clearTimeout(kick_timer);
}
else {
redirect();
}
};
//schedule idler
setInterval(idler, idle_timer);

Hide download link for 10 seconds? js

hey, how can I have my download link hidden, and make a count down type thing. Maybe have it count down from 10 and once it's done that have the download link appear, it would be best to do it in js right?
does anyone know how to do this? :D
Thanks
Complete example:
<span id="countdown"></span>
<a id="download_link" href="download.zip" style="display:none;">Download</a>
<noscript>JavaScript needs to be enabled in order to be able to download.</noscript>
<script type="application/javascript">
(function(){
var message = "%d seconds before download link appears";
// seconds before download link becomes visible
var count = 10;
var countdown_element = document.getElementById("countdown");
var download_link = document.getElementById("download_link");
var timer = setInterval(function(){
// if countdown equals 0, the next condition will evaluate to false and the else-construct will be executed
if (count) {
// display text
countdown_element.innerHTML = "You have to wait %d seconds.".replace("%d", count);
// decrease counter
count--;
} else {
// stop timer
clearInterval(timer);
// hide countdown
countdown_element.style.display = "none";
// show download link
download_link.style.display = "";
}
}, 1000);
})();
</script>
You can use setInterval for this. setInterval behaves like a timer, where you can run a certain function periodically. Something like this should do the work(untested):
$(".link").hide();
var iteration = 0;
var timer = setInterval(function() {
if(iteration++ >= 10) {
clearTimeout(timer);
$(".link").show();
$(".counter").hide();
}
$(".counter").text(10 - iteration);
}, 1000);
This will initially hide the download link and run a function every second which counts down from 10. When we reaced ten, we hide the counter and show the link. ClearTimeout is used so that we don't count after we reached ten. Easy as dell.
Edit: As mentioned in the comments, this function is using jQuery to find the elements.
Take a look at the setTimeout function. You can do something like:
function displayLink() {
document.getElementById('link_id').style.display = 'block';
}
setTimeout(displayLink, 10000);
var WAIT_FOR_SECONDS = 10;
var DOWNLOAD_BUTTON_ID = "btnDownload";
if (document.body.addEventListener) {
document.body.addEventListener("load", displayDownloadButton, false);
} else {
document.body.onload = displayDownloadButton;
}
function displayDownloadButton(event) {
setTimeout(function() {
_e(DOWNLOAD_BUTTON_ID).style.display = "";
}, WAIT_FOR_SECONDS*1000);
}
function _e(id) {
return document.getElementById(id);
}

Categories

Resources