Refreshing page - javascript

Am having a problem with my script
i want to refresh the page every 30 seconds,
But ONLY when you are NOT typing into textbox
OTHER IMPORTANT THING
page should refresh if am typing into textbox and i stop without clicking send button for 1 minute (Idle)
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
var isTyping = false;
$("#inputbox").focus(function() {
isTyping = true;
});
$("#inputbox").blur(function() {
isTyping = false;
});
// Refresh page, but ONLY when you are NOT typing
var refreshId = setInterval(function() {
if (!isTyping) {
window.setTimeout( function() {
window.location.reload();
)}, 30000);
}
)}
$.ajaxSetup({ cache: false });
</script>
</head>
<body>
<input type="text" id="inputbox">
<button type="button">Click Me!</button>
</body>
</html>

Rather than check for "isTyping", you can cancel the setTimeout and create a new one each time the user does something.
Cancel/start a new timer (60s) on focus/input.
Cancel/start a new timer (30s) on blur.
Start the timeout when the page loads.
Here's the implementation (timeout changed to x100 ms instead of x1000 just for testing and some output to see what's happening)
var timerId;
function restartTimer(s) {
clearInterval(timerId);
timerId = setTimeout(() => {
//window.location.reload()
$("#out").text("times up");
}, s * 100 /* * 1000, 100 for testing */);
$("#out").text("timer restarted: " + s + "s " + timerId);
}
$("input").on("focus input", () => restartTimer(60));
$("input").on("blur", () => restartTimer(30));
// "technically" startTimer, but it's the same
restartTimer(30);
// optionally only if "idle"
//$("document").on("mousemove click", () => restartTimer(30));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<input type="text" id="inputbox">
<button type="button">Click Me!</button>
<div id="out"></div>

Related

JavaScript one click button

Please I want to create a button that can be clicked only once in 24hrs in js but I don't really know how to put it up.
<html>
<head>
<title>Disable Button</title>
<script>
function doSomething () {
document.getElementById("myButton").disabled = true;
document.getElementById("myButton").disabled = false;}
</script>
</head>
<body>
<input type="button" id="myButton" onclick="doSomething()"
value="Click Here To Do Something"/>
</body>
</html>
window.onload = () => {
//on load of the page it will check for same day and disable/enable.
let lastclicked = localStorage.getItem('lastclicked') || '';
document.getElementById("myButton").disabled = lastclicked === new Date().toDateString();
}
function doSomething () {
localStorage.setItem('lastclicked', new Date().toDateString());
document.getElementById("myButton").disabled = true;
}
you need to save to date and time of the last trigger somewhere in local storage or cookies so next when the button is triggered it checked the date in storage if that exists then it will check the date.
hope so it will work for you.
var todayclick = true;
var buttonval = document.getElementById("myButton");
buttonval.click(function() {
if (todayclick ) {
alert("Error!");
}
else {
variable += 1;
todayclick = false;
}
setTimeout(function() {
todayclick = true;
}, 86400);
});

How to call a setInterval function

Instead of setInterval running upon refresh, I'd like it to run upon clicking on the start button & go up to time. I tried almost every variation for the past hours & it didn't work without any errors.
Instead the timer stops which makes sense if time > 2. Therefore, I am not sure how I can make timer restart once start gets click and for the timer to stop once time reached (i.e. 2 seconds)
HTML
<script src='https://api.chipware.co.za/js/flipclock-min.js'></script><script src="./script.js"></script>
<button style="width:200px; height: 50px;" id="start">Start</button>
<button style="width:200px; height: 50px;"onclick="submit()" id="stop">Submit</button>
JS
let time = 2;
var clock = $('.clock').FlipClock(0, {
clockFace: 'HourlyCounter',
countdown: false });
function submit(){
clock.stop();
}
var element_ = document.getElementById("start");
element_.addEventListener('click', function(){
start(time);
});
function start(time){
countup = setInterval(function () {
if(clock.getTime().time > time) {
clock.stop();
clearInterval(countup);
}
else{
var element = document.getElementById("stop");
element.addEventListener('click', function(){
submit();
});
}
})};
Also unsure why this code runs w/o error by itself but in chrome extension, it gives:
Uncaught TypeError: $(...).FlipClock is not a function
Your missing flipclock library I just added and update the code now it work.
let time = 2;
var clock = $('.clock').FlipClock(0, {
clockFace: 'HourlyCounter',
countdown: false });
function submit(){
clock.stop();
}
var element_ = document.getElementById("start");
element_.addEventListener('click', function(){
start(time);
});
function start(time){
countup = setInterval(function () {
console.log(clock.getTime().time ,time)
if(clock.getTime().time > time) {
clock.stop();
clearInterval(countup);
}
else{
var element = document.getElementById("stop");
element.addEventListener('click', function(){
submit();
});
}
})};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/flipclock/0.7.7/flipclock.min.js" integrity="sha512-Vy4ftjkcjamOFPNSK7Osn8kYhF7XDcLWPiRvSmdimNscisyC8MkhDlAHSt+psegxRzd/q6wUC/VFhQZ6P2hBOw==" crossorigin="anonymous"></script>
<button style="width:200px; height: 50px;" id="start">Start</button>
<button style="width:200px; height: 50px;"onclick="submit()" id="stop">Submit</button>

Javascript: Automatically clicking a button when countdown is complete

I am trying to display the alert message when the countdown is complete, I am trying the following code but its does not work please help!
<!DOCTYPE html>
<html>
<body>
<p id=count></p>
<form>
<button id="autoClickBtn" onclick="autoClick()">Click me</button>
</form>
<script>
function autoClick(){alert("I am loaded and automatically clicked");}
var count = 5;
var interval = setInterval(function () {
document.getElementById('count').innerHTML = count;
count--;
if (count === -1) {
clearInterval(interval);
window.onload = function () { document.getElementById("autoClickBtn").click() };
}
}, 1000 );
</script>
</body>
</html>
If you want to alert once after a certain time. Use setTimeout function. You can add the delay in milliseconds. In the example below I have added a delay of 2 secs.
setInterval, on the other hand, will run indefinitely again and again after time period defined
setTimeout(function () {
window.alert('This is an alert');
}, 2000);

Problems with running 2 JavaScript "onload" functions

I have two JavaScript "onload" functions that I am trying to run on a webpage: a visual timer and a auto refresh function. I have implemented both in my webpage but although the timer runs, the Auto Refresh function will not run unless I remove the visual timer function from the script.
Here is the code for the webpage:
<!DOCTYPE html>
<HTML>
<HEAD>
<script type="text/JavaScript">
<!--
function timedRefresh(timeoutPeriod) {
setTimeout("location.reload(true);",timeoutPeriod);
}
// -->
</script>
<TITLE>test</TITLE>
</head>
<body onload="JavaScript:timedRefresh(15000); timedText();">
<script>
window.onload = timedText;
function timedText() {
var txt = document.getElementById('txt'),
counter = 15;
var timer = setInterval(function () {
if(counter === 0) return clearInterval(timer);
txt.value = counter + " seconds";
counter--;
}, 1000);
}
</script>
<input type="text" id="txt" />
</body></HTML>
Any help in solving this problem would be greatly appreciated.
try with a small change:call timedRefresh() inside window.onload's timetext() function not in body onload.
<!DOCTYPE html>
<HTML>
<HEAD>
<script type="text/JavaScript">
<!--
function timedRefresh(timeoutPeriod) {
setTimeout("location.reload(true);",timeoutPeriod);
}
// -->
</script>
<TITLE>test</TITLE>
</head>
<body>
<script>
window.onload = timedText;
function timedText() {
var txt = document.getElementById('txt'),
counter = 15;
timedRefresh(15000);
var timer = setInterval(function () {
if(counter === 0) return clearInterval(timer);
txt.value = counter + " seconds";
counter--;
}, 1000);
}
</script>
<input type="text" id="txt" />
</body></HTML>
The problem is the second one overrides the first. That is what you should be using addEventListener to add events.
window.addEventListener('load', timedText, false);
window.addEventListener('load', function(){timedRefresh(15000);}, false);
and if you need to support older IEs you need to look at attachEvent
BUT looking at the code why are you running two setTimeouts when all you need to do is when it hits zero call the redirect.
You can add multiple onload events using the addEventListener method, like so:
window.addEventListener("load", timedText, false);
window.addEventListener("load", timedRefresh(15000), false);
function timedText() {
var txt = document.getElementById('txt'),
counter = 15;
var timer = setInterval(function() {
if (counter === 0) return clearInterval(timer);
txt.value = counter + " seconds";
counter--;
}, 1000);
}
function timedRefresh(timeoutPeriod) {
setTimeout("location.reload(true);",
timeoutPeriod);
}
You can find out more information about addEventListener here.
Here's a working codepen.

jQuery countdown running when it's paused

I'm using Keith Wood's jQuery Countdown timer. http://keith-wood.name/countdown.html
What I want to achieve is a countup with stop and resume buttons, and controls to add and subtract minutes and seconds:
I create a countup (from 0 to 60 minutes) and pause it right away, like this:
$('#contador_tiempo').countdown({
since: 0,
format: 'MS',
layout: '{mnn}{sep}{snn}'
});
$('#contador_tiempo').countdown('pause');
But it seems that it's still running in the background. When I click the buttons to add or subtract, the functions do the operations on top of that background counter, not the displayed counter.
Full code on JSFiddle, with the behaviour reproduced:
http://jsfiddle.net/J2XHm/4/
(Play a bit with the controls and you will see that it keeps counting although it's paused.)
Yes, there is a bug in the 'getTimes' command - it recalculates when paused. I'll make the correction in the next release (1.6.2) but in the meantime you can change the _getTimesPlugin function:
_getTimesPlugin: function(target) {
var inst = $.data(target, this.propertyName);
return (!inst ? null : (inst._hold == 'pause' ? inst._savePeriods : (!inst._hold ? inst._periods :
this._calculatePeriods(inst, inst._show, inst.options.significant, new Date()))));
},
If you can accept lightweight code, i.e. without using the jQuery countdown timer, the following might help you:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="http://localhost/web/JavaScript/jQuery/jquery"></script>
<script type="text/javascript">
var countUpSeconds = 0;
var interval = null;
function displayTime() {
$("#timeContainer").text(format(Math.floor(countUpSeconds/60))+":"+format(countUpSeconds%60));
}
function playStop() {
if(interval) {interval=window.clearInterval(interval);}
else {interval = window.setInterval(countUp, 1000);}
}
function countUp() {
++countUpSeconds;
if(countUpSeconds >= 3600) {/* do something when countup is reached*/}
displayTime();
}
function format(s) {return s<10 ? "0"+s : s;}
$(function() {
displayTime();
$("#playStop").on("click", function () { playStop(); } );
$("#addMin").on("click", function () { countUpSeconds += 60; displayTime(); } );
$("#subMin").on("click", function () { countUpSeconds = Math.max(0, countUpSeconds-60); displayTime(); } );
$("#addSec").on("click", function () { countUpSeconds += 1; displayTime(); } );
$("#subSec").on("click", function () { countUpSeconds = Math.max(0, countUpSeconds-1); displayTime(); } );
});
</script>
</head>
<body>
<div id="timeContainer"></div>
<button id="playStop">Play/Stop</button>
<button id="addMin">+1 minute</button>
<button id="subMin">-1 minute</button>
<button id="addSec">+1 second</button>
<button id="subSec">-1 second</button>
</body>
</html>

Categories