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>
Related
When the start button is clicked once, everything works perfectly fine. However, when the start button is clicked multiple times (by accident for example), the speed of the counter increases and the stop button doesn't seem to work any more!
Why is this happening? And what can I do to prevent the start button (if clicked accidentally) from increasing the speed of the timer when it is already running?
<button id="startBtn" onclick="startTimer()">Start</button>
<button id="stopBtn" onclick="stopTimer()">Stop</button>
<h2 id="timer"></h2>
<script>
let myCounter
function startTimer() {
myCounter = setInterval(counter, 200);
}
function stopTimer() {
clearInterval(myCounter);
}
let i = 0;
function counter() {
document.getElementById("timer").innerHTML = i++;
}
</script>
Welcome to StackOverflow.
Within your question, it's unclear if you want the timer to reset if the user clicks the start button again, however with my answer, I came to the conclusion that you didn't.
Here's a modified version of startTimer() which utilizes a guard clause to check if an interval already exists (and if so, don't start again)
function startTimer() {
// Guard clause! If the counter exists, exit the function!
if(myCounter) {
return
}
myCounter = setInterval(counter, 200);
}
A tiny update of the stop function is also needed to set myCounter to null after the counter is stopped:
function stopTimer() {
clearInterval(myCounter);
// Set the counter to Null, because it is still declared even though it has no value! (try removing this line and see what happens when you hit start again)
myCounter = null;
}
Hope this helped :)
I added a variable that can helps you detect if the counter is already clicked or not, with the condition of that variable, you can have what you want, I edited your code.
<button id="startBtn" onclick="startTimer()">Start</button>
<button id="stopBtn" onclick="stopTimer()">Stop</button>
<h2 id="timer"></h2>
<script>
let myCounter
let clicked = false;
function startTimer() {
if(!clicked){
myCounter = setInterval(counter, 200);
}
clicked = true;
}
function stopTimer() {
if(clicked){
clearInterval(myCounter);
}
clicked = false;
}
let i = 0;
function counter() {
document.getElementById("timer").innerHTML = i++;
}
</script>
You could simply disable the start button once clicked, and re-enable it when the stop button is clicked.
let i = 0;
let myCounter;
let startBtn = document.getElementById('startBtn');
let stopBtn = document.getElementById('stopBtn');
let timer = document.getElementById('timer');
function startTimer() {
startBtn.disabled = true;
stopBtn.disabled = false;
myCounter = setInterval(counter, 200);
}
function stopTimer() {
startBtn.disabled = false;
stopBtn.disabled = true;
clearInterval(myCounter);
}
function counter() {
i++; timer.value = i;
}
startBtn.addEventListener('click', startTimer);
stopBtn.addEventListener('click', stopTimer);
<button id="startBtn">Start</button>
<button id="stopBtn" disabled>Stop</button>
<h2><output id="timer">0</output></h2>
As an added measure, you can even hide the disabled button so only the active one is shown.
button:disabled {
display: none;
}
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>
I'm working with jQuery Flipclock
It's working good.
Then now I have button modify time, if I click it then the time will be change to 10 seconds and print the text into span info. But why the old counting value is still appear? How to print into span info only 10 seconds (on button click) without show the old counting value?.
$('.modifytime').on('click', function() {
countdown(10);
});
function countdown(b) {
if (b == undefined) {
a = 15;
} else {
a = 10
}
clock = $('.clock').FlipClock(a, {
clockFace: 'MinuteCounter',
countdown: true,
autoStart: true,
callbacks: {
start: function() {
$('.message').html('The clock has started!');
},
interval: function() {
var time = this.factory.getTime().time;
$('.info').html(time);
},
stop: function(){
alert("Counting done");
}
}
});
}
countdown();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link href="https://kms.puksiix.com/flipclock.css" rel="stylesheet" />
<script src="https://kms.puksiix.com/flipclock.js"></script>
<div class="clock"></div>
<span class="info"></span>
<button class="modifytime">Modify</button>
UPDATED
If I put this script:
stop: function(){
alert("Counting done");
}
It always show me "Counting done" even I just click the button.
The documentation of that rather outdated library seems to no longer exist. However if you look through the source of the library in Github you can see there is a stop() method which can be called on the instance.
To retain a reference to the instance between button clicks you can store it in the data alongside the .clock element, something like this:
let $clock = $('.clock');
$('.modifytime').on('click', function() {
countdown(10);
});
function countdown(delay) {
delay = delay || 100;
// check for previous instance and stop it counting down
let prevInstance = $clock.data('flipclock');
if (prevInstance)
prevInstance.stop();
let clockInstance = $clock.FlipClock(delay, {
clockFace: 'MinuteCounter',
countdown: true,
autoStart: true,
callbacks: {
start: function() {
$('.message').html('The clock has started!');
},
interval: function() {
var time = this.factory.getTime().time;
$('.info').html(time);
}
}
});
// save new instance in element metadata
$clock.data('flipclock', clockInstance);
}
countdown();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link href="https://kms.puksiix.com/flipclock.css" rel="stylesheet" />
<script src="https://kms.puksiix.com/flipclock.js"></script>
<div class="clock"></div>
<span class="info"></span>
<button class="modifytime">Modify</button>
A quick perusal of the source shows you can .stop the existing clock before starting a new one:
clock.stop();
Add this to your countdown() function. Snippet includes a second button to stop to show this working independently.
$('.modifytime').on('click', function() {
countdown(10);
});
$(".stop").on("click", function() { clock.stop(); });
var clock;
function countdown(b) {
if (b == undefined) {
a = 100;
} else {
a = 10
}
if (clock) clock.stop();
clock = $('.clock').FlipClock(a, {
clockFace: 'MinuteCounter',
countdown: true,
autoStart: true,
callbacks: {
start: function() {
$('.message').html('The clock has started!');
},
interval: function() {
var time = this.factory.getTime().time;
$('.info').html(time);
}
}
});
}
countdown();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link href="https://kms.puksiix.com/flipclock.css" rel="stylesheet" />
<script src="https://kms.puksiix.com/flipclock.js"></script>
<div class="clock"></div>
<span class="info"></span>
<button class="modifytime">Modify</button>
<button class="stop">Stop</button>
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);
I created one tab A, B, C. Each tab has a html page. If I click 1st tab, I have set a timeout function(javascript) for automatic logout. If I am clicking 2nd tab,the same timeout function running. But I want to stop /reset the 1st tab timer.
function timeout(){
var IDLE_TIMEOUT = 60; //seconds
var _idleSecondsTimer = null;
var _idleSecondsCounter = 0;
document.onclick = function() {
_idleSecondsCounter = 0;
};
document.onmousemove = function() {
_idleSecondsCounter = 0;
};
document.onkeypress = function() {
_idleSecondsCounter = 0;
};
_idleSecondsTimer = window.setInterval(CheckIdleTime, 1000);
function CheckIdleTime() {
_idleSecondsCounter++;
if (_idleSecondsCounter >= IDLE_TIMEOUT) {
window.clearInterval(_idleSecondsTimer);
alert("Time expired!");
document.location.href = "logout.php";
}
}
}
function opentab1(){
document.getElementById("tab1").innerHTML='<object type="text/html" data="tab1.php" ></object>';
}
function opentab2(){
document.getElementById("tab2").innerHTML='<object type="text/html" data="tab2.php" ></object>';
}
function opentab3(){
document.getElementById("tab3").innerHTML='<object type="text/html" data="tab3.php" ></object>';
}
function opentab4(){
document.getElementById("tab4").innerHTML='<object type="text/html" data="tab4.php" ></object>';
}
<body>
<div class="tab1" onload="timeout()" onclick="opentab1()">
</div>
<div class="tab2" onload="timeout()" onclick="opentab2()">
</div>
<div class="tab3" onload="timeout()" onclick="opentab3()">
</div>
<div class="tab4" onload="timeout()" onclick="opentab4()">
</div>
// loading an php file using on click function
<div class="container" id="tab1"></div>
<div class="container" id="tab2"></div>
<div class="container" id="tab3"></div>
<div class="container" id="tab4"></div>
</body>
Thanks in advance. Please guide.
You can make use of setTimeout().
The clearTimeout() method clears a timer set with the setTimeout() method.
The ID value returned by setTimeout() is used as the parameter for the clearTimeout() method.
Note: To be able to use the clearTimeout() method, you must use a global variable when creating the timeout method:
Syntax:
myVar = setTimeout("javascript function", milliseconds);
Then, if the function has not already been executed, you will be able to stop the execution by calling the clearTimeout() method.
Example:
var myVar;
function myFunction() {
myVar = setTimeout(function(){ alert("Hello"); }, 3000);
}
function myStopFunction() {
clearTimeout(myVar);
}
In your case:
window.timeout1 = setTimeout(function() {
_idleSecondsCounter++;
if (_idleSecondsCounter >= IDLE_TIMEOUT) {
window.clearInterval(_idleSecondsTimer);
alert("Time expired!");
document.location.href = "logout.php";
}
}, 1000);
function stopTimeout1() {
clearTimeout(window.timeout1);
}
You can stop the timer whenever a new tab is clicked by editing your methods and stopping the current timer then starting a new one.
You can remove the onload from the divs
<div class="tab1" onload="timeout()" onclick="opentab1()">
to
<div class="tab1" onclick="opentab1()">
And then in your functions for retrieving the tab content, for example opentab1() edit them like the function below
function opentab2(){
//clear the previous timer
clearInterval(interval_name);
//start a new timer
timeout();
document.getElementById("tab2").innerHTML='<object type="text/html" data="tab2.php" ></object>';
}