issue with if else conditional - javascript

When the page is open, it automatically set's a timeout to preform a task.
What i want is to change the timing if an event occur. If the user click a button, it changes the time right after the click.
If the user does nothing, the page should auto refresh after a given time, if the user click on "#b1" , the initial timeout should be interrupted and beggin a new one with other time set
I've tried the previous code, but it only executes the last alert .
How can i accomplish this ?
var clicked = 0;
var time = '';
$('#b1').click(function() {
clicked = 1;
});
if (clicked == 1) {
time = 10;
setTimeout(function() {
alert('clicked');
}, time);
} else {
time = 10000;
setTimeout(function() {
alert('nothingDone');
}, time);
}

Define a global variable where setTimeout is the value, call clearTimeout() with variable as parameter if user clicks #b1 element, then set variable to setTimeout() call within event handler
$(function() {
var clicked = 0;
var time = '';
var timer;
function updateTimer() {
time = 10;
timer = setTimeout(function() {
alert('clicked');
}, time);
}
$('#b1').click(function() {
clicked = 1;
clearTimeout(timer);
updateTimer()
});
if (clicked == 1) {
updateTimer()
} else {
time = 10000;
timer = setTimeout(function() {
alert('nothingDone');
}, time);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="b1">click</div>

Related

Pure JavaScript: How to refresh page after countdown if the browser tab is active

I want to achieve the following scenario:
Set a timer of 60 seconds and start the countdown displaying the
timer. After the countdown is finished, refresh (not reload) the page
and restart the countdown timer and continue the process.
If the browser's tab is changed, after finishing the timer, refresh the
page and pause the timer, and only when the tab is active again refresh
the page and start the countdown timer again.
I have managed to achieve the first requirement like:
Result will Refresh in <span id="countdown"></span>
<script>
if (!document.hidden) {
function timedRefresh(e) {
var n = setInterval((function () {
e > 0 ? (e -= 1, document.getElementById("countdown").innerHTML = e) : (clearInterval(n), window.location.reload())
}), 1e3)
}
timedRefresh(59)
}
</script>
And is unable to achieve the second requirement. I have tried to implement the solution mentioned here: Is there a way to detect if a browser window is not currently active?
But it didn't work.
How do I achieve the requirements in pure JavaScript code?
The following code has solved this scenario. It's a little messy, but I think is understandable. We use both window.document.hasFocus() and the focus event to create this solution. I have changed the window.location.reload() methods to just consoles simulating a function that refresh the data inside the application, since is asked to us refresh (not reload).
function timedRefresh(intervalTime) {
let interval = null;
let currentTime = intervalTime;
const updateTimer = () => {
const countdownSpan = document.getElementById("countdown");
if (currentTime <= 0) {
console.log(`print refresh at ${new Date()}`); // refresh page
if (window.document.hasFocus()) {
currentTime = intervalTime;
} else {
clearInterval(interval);
interval = null;
currentTime = intervalTime;
}
}
if (!interval) {
countdownSpan.innerHTML = "#";
} else {
countdownSpan.innerHTML = currentTime;
currentTime -= 1;
}
};
interval = setInterval(updateTimer, 1000);
window.addEventListener("focus", () => {
if (!interval) {
interval = setInterval(updateTimer, 1000);
}
});
}
const TIMER_SECONDS = 5;
timedRefresh(TIMER_SECONDS);
Edit:
The answer above does not work with reloads using window.location.realod(). A code solving the issue may look like this:
const TIMER_SECONDS = 60;
/*
* Update span with current time
* `currentTime` is an integer bigger than zero or a string '#' meaning 'timer stopped'
*/
function updateDisplayTimer(currentTime){
const countdownSpan = document.getElementById("countdown");
countdownSpan.innerHTML = currentTime;
}
/*
* A timer with `loopDuration` seconds. After finished, the timer is cleared.
* `loopDuration` is an integer bigger than zero, representing the time duration in seconds.
*/
function timedRefresh(loopDuration) {
let currentTime = loopDuration;
let interval = setInterval(() => {
if (currentTime > 0) {
updateDisplayTimer(currentTime);
currentTime -= 1;
} else {
window.location.reload(); // refresh page
}
}, 1000);
window.addEventListener('load', () => {
if(window.document.hasFocus()){
timedRefresh(TIMER_SECONDS);
} else {
updateDisplayTimer("#");
clearInterval(interval);
interval = null;
}
});
window.addEventListener('focus', () => {
if(interval == null){
window.location.reload(); // refresh page
}
});
}
// exeute main fucntion
timedRefresh(TIMER_SECONDS);
Use window.document.hasFocus() to determine if the user is focused on your webpage or not.

Disable the click and reset it (Javascript Vanilla)

I have a problem. I created the following code! when you click on a button, a timer that lasts 3 seconds starts, the problem is that if I double click the button, the seconds go crazy, I would like to make sure that the click is reset as soon as the timer reaches 0! so that clicking again the timer always starts from 3 seconds!
document.getElementById("titolo").style.display="block"
count = 3 ;
setInterval(function(){
count--;
if(count>=0){
id = document.getElementById("titolo");
id.innerHTML = count;
}
if(count === 0){
document.getElementById("titolo").style.display="none" ;
}
},1000);
setInterval returns an ID that you can pass to clearInterval to cancel it. When the user clicks, cancel the existing ID and call setInterval again to reset it.
Capture the return value of setInterval so that later you can use it to call clearInterval.
You should disable (or hide) the button (or other element) that the user can click to start the count down.
Make sure to always declare your variables with var, let or const.
Don't use innerHTML when you only want to assign text (not HTML entities). For text (like the string representation of a counter) use textContent.
Here is how it could work:
let start = document.getElementById("start");
let id = document.getElementById("titolo");
start.addEventListener("click", function () {
start.disabled = true;
id.style.display = "block";
id.textContent = "3";
let count = 3;
let timer = setInterval(function(){
count--;
id.textContent = count;
if (count === 0) {
id.style.display = "none" ;
clearInterval(timer);
start.disabled = false;
}
}, 1000);
});
<button id="start">Start</button>
<div id="titolo"></div>
The function setInterval returns the unique id representing the interval. You can call the function clearInterval to delete that interval.
Example:
var intervalID = setInterval(function () { }, 0);
clearInterval(intervalID);
Example combined with your code:
var intervalID, count, dom = document.querySelector("#titolo");
document.querySelector("#button").addEventListener("click", onClick);
function onClick() {
clearInterval(intervalID);
dom.style.display = "block";
dom.textContent = 3;
count = 3;
intervalID = setInterval(function() {
count -= 1;
if (count >= 0) dom.textContent = count;
else {
dom.style.display = "none";
clearInterval(intervalID);
}
}, 1000);
}
<div id="titolo"></div>
<button id="button">Button</button>

timer starts automatically instead of on a button press in javascript

I'm quite new to javascript so the answer is probably quite easy but anyways
I'm trying to make a simple click speed test but i cant get the timer to start when the user presses the click me button, so i resorted to just starting it automatically. if anyone can help me to start it on the button press it will be much appreciated
HTML code:
<button id="click2" onclick="click2()">Click Me!</button><br>
<span id="clicksamount">0 Clicks</span><br><br>
<span id="10stimer">10s</span>
JS code:
var click = document.getElementById("click2");
var amount = 0;
var seconds = 10;
var endOfTimer = setInterval(click2, 1000);
function click2() {
seconds--;
document.getElementById("10stimer").innerHTML = seconds + "s";
if (seconds <= 0) {
var cps = Number(amount) / 10;
document.getElementById("clicksamount").innerHTML = "You got " + cps + " CPS!";
document.getElementById("click2").disabled = true;
document.getElementById("10stimer").innerHTML = "Ended";
clearInterval(seconds);
}
}
document.getElementById("click2").onclick = function() {
amount++;
document.getElementById("clicksamount").innerHTML = amount + " Clicks";
}
It looks like you're overwriting your onclick function on the button with id click2 with the lowest 4 lines.
Also, you call clearInterval() with the seconds variable instead of the actual interval, which is referenced by endOfTimer.
I'd suggest to have a separated timer management in a function which you call only on the first click of your button.
See JSFiddle
<button id="clickbutton" onclick="buttonClick()">Click Me!</button><br>
<span id="clicksamount">0 Clicks</span><br><br>
<span id="secondcount">10s</span>
// We will have timerStarted to see if the timer was started once,
// regardless if it's still running or has already ended. Otherwise
// we would directly restart the timer with another click after the
// previous timer has ended.
// timerRunning only indicates wether the timer is currently running or not.
var timerStarted = false;
var timerRunning = false;
var seconds = 10;
var clickAmount = 0;
var timer;
function buttonClick() {
if (!timerStarted) {
startTimer();
}
// Only count up while the timer is running.
// The button is being disabled at the end, therefore this logic is only nice-to-have.
if (timerRunning) {
clickAmount++;
document.getElementById("clicksamount").innerHTML = clickAmount + " Clicks";
}
}
function startTimer() {
timerStarted = true;
timerRunning = true;
timer = setInterval(timerTick,1000);
}
function timerTick() {
seconds--;
document.getElementById("secondcount").innerHTML = seconds + "s";
if (seconds <= 0) {
timerRunning = false;
clearInterval(timer);
var cps = Number(clickAmount) / 10;
document.getElementById("clickbutton").disabled = true;
document.getElementById("clicksamount").innerHTML = "You got " + cps + " CPS (" + clickAmount + "clicks in total)!";
}
}
I made some changes to your code. Effectively, when the user clicks the first time, you start the timer then. The timer variables is null until the first the user clicks.
var click = document.getElementById("click2");
var noOfClicks = 0;
var seconds = 10;
var timer = null;
function doTick(){
seconds--;
if(seconds<=0){
seconds = 10;
clearInterval(timer);
document.getElementById("10stimer").innerHTML= "Ended"
timer=null;
document.getElementById("click2").disabled = true;
}
updateDisplay()
}
function updateClicks(){
if(!timer){
timer=setInterval(doTick, 1000);
clicks= 0;
seconds = 10;
}
noOfClicks++;
updateDisplay();
}
function updateDisplay(){
var cps = Number(noOfClicks) / 10;
document.getElementById("clicksamount").innerHTML = "You got " + cps + " CPS!";
document.getElementById("10stimer").innerHTML =seconds;
}
click.addEventListener('click', updateClicks)
https://jsbin.com/bibuzadasu/1/edit?html,js,console,output
function timer(startEvent, stopEvent) {
let time = 0;
startEvent.target.addEventListener(startEvent.type, () => {
this.interval = setInterval(()=>{
time++;
}, 10); // every 10 ms... aka 0.01s
removeEventListener(startEvent.type, startEvent.target); // remove the listener once we're done with it.
stopEvent.target.addEventListener(startEvent.type, () => {
clearInterval(this.interval); // stop the timer
// your output function here, example:
alert(time);
removeEventListener(stopEvent.type, stopEvent.target); // remove the listener once we're done with it.
});
});
}
Use event listeners rather than onclicks
usage example:
HTML
<button id="mybutton">Click me!</button>
JS
/* ABOVE CODE ... */
let mybutton = document.getElementById("mybutton");
timer(
{target: mybutton, type: "click"},
{target: mybutton, type: "click"}
);
function timer(startEvent, stopEvent) {
let time = 0;
startEvent.target.addEventListener(startEvent.type, () => {
this.interval = setInterval(()=>{
time++;
}, 10); // every 10 ms... aka 0.01s
removeEventListener(startEvent.type, startEvent.target); // remove the listener once we're done with it.
stopEvent.target.addEventListener(startEvent.type, () => {
clearInterval(this.interval); // stop the timer
// your output function here, example:
alert(time);
removeEventListener(stopEvent.type, stopEvent.target); // remove the listener once we're done with it.
});
});
}
let mybutton = document.getElementById("mybutton");
timer(
{target: mybutton, type: "click"},
{target: mybutton, type: "click"}
);
<button id="mybutton">Click me!</button>
//state initialization
var amount = 0;
var seconds = 10;
var timedOut=false;
var timerId=-1;
//counters display
var clicksDisplay= document.getElementById("clicksamount");
var timerDisplay= document.getElementById("10stimer");
function click2(e){
//first click
if(timerId===-1){
//start timer
timed();
}
//still in time to count clicks
if(!timedOut){
amount++;
clicksDisplay.innerText=amount +" Clicks";
}
}
function timed(){
//refresh timer dispaly
timerDisplay.innerText=seconds+"s";
seconds--;
if(seconds<0){
//stop click count
timedOut=true;
}else{
//new timerId
timerId=setTimeout(timed,1000);
}
}

Popup after user has been idle

I have written some code that brings up a message for the user to either ignore the message or go to another page if they have been idle for more than a minute. Everything works, as I want it to except when the user ignores the message. Here is my code:
if ( valid ) {
var idleTime = 0;
jQuery(document).ready(function () {
var idleInterval = setInterval(timerIncrement, 60000);
});
function resetTimer() {
idleTime = 0;
}
jQuery(document)
.on('mousemove', resetTimer)
.on('keydown', resetTimer)
.on('scroll', resetTimer);
function timerIncrement() {
idleTime = idleTime + 1;
if (idleTime >= 1) {
jQuery('#popup').show();
}
jQuery(window).unbind();
}
jQuery('#popupClose').click(function() {
jQuery('#popup').hide();
});
}
I want the popup to not repopulate after they click #popupClose.
I'd do it like this. Just define a start time when you initialize your script. Let an interval run that checks how much time has passed. If it's more than your time wished show the dialog. if not hide it. Also reset the timer on your events.
Your javascript will look like this
$('#btclose').on('click', function(){
clearInterval(interv);
$('#popup').hide();
});
var start = new Date();
var interv = setInterval(function(){
var now = new Date();
console.log()
if(now-start > 5*1000){
$('#popup').show();
}
},10);
$('body').on('mousedown click mousemove', function(){
start = new Date();
});
Here's my fiddle
https://jsfiddle.net/c2L7wpn3/8/
Seems to work. Let me know if this helps
You can either store the information in a cookie, or with a flag (depending on whether you want the popup on each pageview or only once, period).
Then, check the flag/cookie before the showing of the popup. For example:
function timerIncrement() {
idleTime = idleTime + 1;
if (idleTime >= 1) {
if (jQuery('#popup').data('closed') == 1){
jQuery('#popup').show();
}
}
jQuery(window).unbind();
}
jQuery('#popupClose').click(function() {
jQuery('#popup').data('closed', 1);
jQuery('#popup').hide();
});

jQuery. How do I select live created element?

Here is the code:
helpers.ajaxModuleFormRequest('blockcallback', $(this), function() {
var timer = $('[data-timer]');
var seconds = timer.data('timer');
var interval = setInterval(function() {
if (seconds == 0) {
clearInterval(interval);
}
timer.text(seconds);
seconds--;
}, 1000);
});
helper.ajaxModuleFormRequest() does an AJAX-request and then in $.ajax.done() method calls callback-function specified in 3rd param.
<div data-timer="20"></div> is inserted in DOM live $.ajax.done() method and I want to select it to start the timer. But the code doesn't work, $('[data-timer]').length returns 0. How can I fix this?
Here's a simplified example, which inserts a <div> dynamically and then starts the timer:
Html:
<html>
<head>Testpage</head>
<body></body>
</html>
JavaScript:
{
$('body').append('<div data-timer="20"></div>');
var timer = $('[data-timer]');
var seconds = timer.data('timer');
if (seconds!==undefined)
{
alert(seconds);
var interval = setInterval(function() {
if (seconds == 0) {
alert('elapsed!');
clearInterval(interval);
}
timer.text(seconds);
seconds--;
}, 1000);
}
else
{
alert("Please specify a timer value!");
}
}
Note that initially the <div> is not there, it is inserted dynamically via
$('body').append('<div data-timer="20"></div>');
If you want to test whether it tests correctly for existance of the timer value, comment the line above, i.e.
// $('body').append('<div data-timer="20"></div>');
and you'll get the alert message "Please specify a timer value!".
Try it on jsfiddle:
jsfiddle
{
$('body').append('<div data-timer="20"></div>');
var timer = $('[data-timer]');
var seconds = timer.data('timer');
if (seconds!==undefined)
{
alert(seconds);
var interval = setInterval(function() {
if (seconds == 0) {
alert('elapsed!');
clearInterval(interval);
}
timer.text(seconds);
seconds--;
}, 1000);
}
else
{
alert("Please specify a timer value!");
}
}
<head>Testpage</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Categories