JavaScript button manipulation according to Time - javascript

I'm developing an app and what i want is when the user clicks any button, this button will be hidden and only shows up after 24 hours. Here's what i've done so far.
<div class="buttons">
<p><button onclick="hide();" type="button" name="button" id="button-he">Validar</button></p>
<p><button onclick="hide();" type="button" name="button" id="button-hse">Validar</button></p>
<p><button onclick="hide();" type="button" name="button" id="button-hre">Validar</button></p>
</div>
<script>
function intervalo(){
var but = document.getElementByTagName("button");
but.style.visibility='hidden';
}
</script>

One way to do this is creating a cookie on the button click, that will last for 24 hours, and then check if the button should be clickable. Limitations of this approach will be if the user clears the cookies, the button will then again become clickable.
Take a look at this w3schools example:
https://www.w3schools.com/js/tryit.asp?filename=tryjs_cookie_username
if you want to make sure that the user cant click the button again within 24 hours, you neeed to save this click event server side.

You can use setTimeout( YOUR_FUNCTION, TIME_TO_WAIT )
The setTimeout() method of the WindowOrWorkerGlobalScope mixin (and
successor to window.setTimeout) sets a timer which executes a function
or specified piece of code once after the timer expires.
The time, in milliseconds (thousandths of a second), the timer should
wait before the specified function or code is executed. If this
parameter is omitted, a value of 0 is used, meaning execute
"immediately"
The method takes time in milliseconds so, you need convert your time to milliseconds.
For 24hr you need to pass 24*60*60*1000 as a parameter.
SNIPPET
function hide(but) {
but.style.visibility = 'hidden';
setTimeout(function(btn) {
but.style.visibility = 'visible';
}.bind(this, but), 1000); // Show after 1 second.
// change 1000 to time you want 24*60*60*1000
}
<div class="buttons">
<p><button onclick="hide(this);" type="button" name="button" id="button-he">Validar</button></p>
<p><button onclick="hide(this);" type="button" name="button" id="button-hse">Validar</button></p>
<p><button onclick="hide(this);" type="button" name="button" id="button-hre">Validar</button></p>
</div>
The method will forget the timer if user refreshes the page.
If you want it to be persistent then you can store the timestamp when user clicks the button into localstorage and check if that time exceeded 24hrs on load of page.
Check this fiddle for Implementation
buttons = ["button-he", "button-hse", "button-hre"];
timer = 24 * 60 * 60 * 10000;
function init () {
buttons.forEach(function(val) {
var start = localStorage.getItem(val + '-timer');
var end = new Date().getTime();
var but = document.getElementById(val);
if (start && (end - start < timer)) {
but.style.visibility = 'hidden';
setTimeout(function(btn) {
but.style.visibility = 'visible';
}.bind(this, but), end-start);
}
})
}
init();
window.hide = function(but) {
localStorage.setItem(but.id + '-timer', new Date().getTime());
but.style.visibility = 'hidden';
setTimeout(function(btn) {
but.style.visibility = 'visible';
}.bind(this, but), 24 * 60 * 60 * 10000); // Show after 1 second.
// change 1000 to time you want 24*60*60*1000
}
Although, I suggest also check at the server side for this logic.
For that just pass the time-stamp when user clicks the button to the server and store it and check for time lapse.

Related

Automate click on a specific button on a website (that only pops up after 30 minutes)

I am trying to automate the clicking of a specific button on a website that only appears after 30 minutes of being logged in to the website. I have already looked in to how to do this but my primary issue is that the button does not have an ID.
The other issue is that this button only appears on the page after roughly 30 minutes, I am experimenting with tampermonkey as a way of running this script in my browser, however I am unsure on how to script it.
I found somebody else with a similar issue - this was their solution
For Each btn In document.getElementsByTagName("button")
If btn.innerText = "Refresh Token Now" Then
btn.Click()
End If
however this does not seem to be working for me, I have also tried the following
For Each btn In document.getElementsByClassName("wb-button wb-button--secondary wb-button--small")
If btn.innerText = "Refresh Token Now" Then
btn.Click();
End If
If somebody could please assist/point me in the right direction I would greatly appreciate it! :)
Use setTimeout and do something after 30 minute being load, 1 sec = 1000
const halfhour = 1000 * 60 * 30;
setTimeout(() => {
console.log('Run after 30 minute');
document.querySelector('.refresh').click();
}, halfhour);
document.querySelectorAll('button').forEach(b => {
if (b.innerText.indexOf('Refresh') != -1) {
b.addEventListener('click', function() {
console.log('Refresh has been click');
});
}
});
<div>
<button class="close">Close</button>
<button class="refresh">Refresh</button>
</div>

Click event doesn't produce any result

total noob here.
I'm writing a countdown timer that starts clicking on a "Start" button. No matter what I do, the timer always starts at the load of the page. And I mean that, when using live server on VS Code, every time I give the page a save, the timer starts.
No error appears in the console.
Probably I'm missing something really basilar, but I would love some help!
const btnStart = document.querySelector('.start');
const startTimer = function() {
let time = 10;
const timer = setInterval(function() {
const min = String(Math.trunc(time/60));
const sec = String(time%60);
time --;
input.value = `${min.length <= 9 ? min.padStart(2, 0) : min}:${sec.length <= 9 ?sec.padStart (2, 0) : sec}`;
if(time == 0){
setTimeout(function(){clearInterval(timer);
startTimer();}, 1000)
}
}, 1000)
}
btnStart.addEventListener('click', startTimer);
Html elements part:
<div class="main-container">
<input type="text" class="input" placeholder="MM:SS">
<div class="buttons-container">
Start
<button class="start">START</button>
Stop
Reset
</div>
</div>
You new edit to the question answered the question.
You're using VSCode LiveShare. When you save, it doesn't actually reload the page, it just loads the changes.
Since you're recursively calling startTimer(); (it's calling itself inside a setTimeout), it will never stop since it's not a full reload.
The easiest way to fix this is to reload your page manually (Ctrl+r or Command+r)
The harder way you could solve this is to store timer as a global variable, and on load, if timer exists, run clearInterval(timer)

Infinite-Loop GoogleAppScript

How can i create an infinite loop that changes a cell value repeatedly in Google-app-script?
function doTest() {
if(x>=360) x = 0;
Utilities.sleep(500);
x = x+1;
SpreadsheetApp.getActiveSheet().getRange('a13').setValue(x);
incr();
}
I would like it to increment a cell value until it reaches 360 and then start from 0.
An infinite loop will eventually crash your app. But assuming that's what you're going for, here's one way to do it:
function iterate() {
var range = SpreadsheetApp.getActiveSheet().getRange('a13');
var i = 0;
while(true) {
range.setValue(i);
SpreadsheetApp.flush();
i = (++i) % 361;
}
}
You want to count up the value of number of cell "A13" on the active Spreadsheet every 0.5 seconds.
You want to loop the number from 0 to 360.
You want to loop this cycle as the infinite loop.
If my understanding is correct, how about this sample script? I think that there are several answers for your situation. So please think of this as just one of them. In this sample script, I used a sidebar. Namely, I used Javascript and Google Apps Script. I thought that the infinite loop might be able to be achieved by running Google Apps Script from the sidebar. I could confirm that in my environment, this count could be run more than the maximum execution time of 6 minutes of Google Apps Script.
Usage:
When you use this script, please do the following flow.
Copy and paste the following script to the script editor (the container-bound script of Spreadsheet).
Run the function of run().
By this, a sidebar is opened on the Spreadsheet.
When you click a button of "start", the number is put to the cell "A13" of the active sheet, and the value is counted up every 0.5 seconds. The number loops the cycle from 0 to 360.
If you want to stop the count, please click "stop" button.
Sample script:
function setValue(v) {
Utilities.sleep(500);
SpreadsheetApp.getActiveSheet().getRange("A13").setValue(v);
}
function run() {
var str = '<input type="button" value="start" onclick="start()"><input type="button" id="stop" value="stop" onclick="stop=false"><script>var stop=false; function work(v){return new Promise((resolve, reject)=> google.script.run.withSuccessHandler(()=> resolve()).setValue(v));}async function start(){stop=true; var i=0; while(stop){await work(i); i=(++i) % 361;}}</script>';
var html = HtmlService.createHtmlOutput(str);
SpreadsheetApp.getUi().showSidebar(html);
}
Expanded HTML:
At above sample script, HTML is minified. Below script is the expanded HTML.
This is only for confirming HTML. So you are not required to copy and paste this.
<input type="button" value="start" onclick="start()">
<input type="button" id="stop" value="stop" onclick="stop=false">
<script>
var stop = false;
function work(v) {
return new Promise((resolve, reject) => google.script.run.withSuccessHandler(() => resolve()).setValue(v));
}
async function start() {
stop = true;
var i = 0;
while(stop) {
await work(i);
i = (++i) % 361; // This is from Dimu Designs's answer.
}
}
</script>
Note:
I used the loop process by Dimu Designs's answer.
References:
Class google.script.run
Class Ui
If this method was not the direction of your goal, I apologize.
The following do the job !
Note the call to flush, this ensures the spreadsheet will be refreshed at each iteration.
Otherwise you won't see the cell update in realtime.
Enjoy ;-)
function doIncrease() {
for(var x=0;;x++){
//Set value
SpreadsheetApp.getActiveSheet().getRange('a13').setValue(x);
//Flush changes to spreadsheet
SpreadsheetApp.flush();
//Wait as long as desired
Utilities.sleep(500);
//Reboot the Endless loop from 0 to 360
if(x==360) x=0;
}
}

How to create a persistent random countdown?

Basically, I need a counter that will go backwards from 100-1 slowly as users enter our website. We are only giving out "100" free coupon but want to give the appearance that users are quickly grabbing them in order to create urgency and have the prospect give us their email. I am using Unbounce to host our mobile landing page.
I came across a similar post to mine but the code generated numbers randomly in the millions. Here is the link for further help: https://stackoverflow.com/a/17964971
Quick example:
Be the first to know when we launch! We are only giving out 100 coupons and there are only (x) amount left.
Click here to get yours!
Count down at a random rate between 5 seconds and 1 second, save the current to the browser so if the user revisits the page the number doesn't reset
(Demo)
var i = 100;
var counter = document.getElementById('counter');
if(localStorage.counter) {
i = localStorage.counter;
}
function countDown() {
if(i > 0) {
i--;
console.log(i);
counter.innerText = i;
localStorage.counter = i;
var timeout = Math.floor(Math.random() * (5000 - 1000)) + 1000;
setTimeout(function(){
countDown();
}, timeout);
} else {
document.getElementById('counter-wrp').innerText = 'Oh no, you missed out! All of the coupons are gone.'
}
}
countDown();
<span id="counter-wrp">Be the first to know when we launch! We are only giving
out 100 coupons and there are only <span id="counter" style="color: red;"></span> left</span>
I create this jsFiddle for you using your example
My method utilizes localStorage, which is perfect for this type of function. You can read more about local storage here w3schools. You need to this save the count.
You will notice that to initialize the counter you need additional options
var counter = new Counter({
start: 123456789,
up: '#btnUp',
down: '#btnDn',
storageKey: 'count'
});
up: and down: are just jQuery selectors for the buttons I added with id's btnUp and btnDn. storagekey: can be whatever string you'd like to set to retrieve our count out of localstorage.
here are my buttons
<div class="buttons">
<button id="btnUp" type="button">+</button>
<button id="btnDn" type="button">-</button>
</div>
I hope this helps

I am trying to clear my countdown when the 'home' button is pressed

so, my issue is that I am trying to get my countdown to clear when i hit the 'back' icon. This is so that if the user clicks back to the timer page it will be reset, not still continuing from when they hit back.
This is the line of code that i think should be doing the trick:
$('.ui-icon-back').click (clearInterval(countdown));
here is my HTML:
<!-- /////////////////
Green Tea
////////////////////// -->
<!--Create section tag-->
<section data-role="page" id="green">
<!--Create header tag-->
<header data-role="header">
<!--Create h1 tag-->
<h1> TEA TIME </h1>
<!--Create a icon that will link back to the home page-->
back
<!--End header-->
</header>
<!--Create h1 tag that states full steep time-->
<h1>Green Tea Takes 2 Minutes</h1>
<!--Show timer duration before timer start-->
<p id="timedisp">120 sec</p>
<!--Call the countdown-->
<div class="clock">
</div>
<!-- Button to trigger the start timer js-->
Start
<!-- Button to trigger the timer restart-->
Reset
<!-- End section tag-->
</section>
Here is my Javascript:
// JavaScript Document
//Green Tea Timer
function greenTea(){
// Set The Duration
var duration = 120;
// Insert the duration into the div with a class of clock
$(".clock").html(duration + " sec");
// Create a countdown interval
var countdown = setInterval(function (greenTea) {
// subtract one from duration and test to see
// if duration is still above zero
if (--duration) {
// Update the clocks's message
$(".clock").html(duration + " sec");
// Otherwise
} else {
// Clear the countdown interval
clearInterval(countdown);
// set a completed message
$(".clock").html("End Your Steep");
}
// Run interval every 1000ms
}, 1000);
};
$("a#start").click(greenTea);
$('#start').click(function(greenTea){
$('#timedisp').hide();
});
$('#reset').click(function(greenTea) {
location.reload();
});
$('.ui-icon-back').click (clearInterval(countdown));
The countdown variable is declared inside the greenTea function. You have to declare it outside the function for it to be accessible from the click handler.
You'll also have to put your jQuery functions inside the jQuery ready function:
var countdown;
function greenTea(){
var duration = 120;
$(".clock").html(duration + " sec");
countdown = setInterval(function (greenTea) {
if (--duration) {
$(".clock").html(duration + " sec");
} else {
clearInterval(countdown);
$(".clock").html("End Your Steep");
}
}, 1000);
};
$(function(){
$("a#start").click(greenTea);
$('#start').click(function(greenTea){
$('#timedisp').hide();
});
$('#reset').click(function(greenTea) {
location.reload();
});
$('.ui-icon-back').click (function(){
clearInterval(countdown));
});
});
When you do:
$(..).click(clearInterval(..));
JavaScript is immediately executing the clearInterval method. You need to do:
$(..).click(function(){
clearInterval(..);
});
After that, you need to put that code inside greenTea function for the clearInterval to be able to access the countdown variable. That or declare the variable countdown outside greanTea. I recommend to do the first one because the second one will pollute the global scope.

Categories

Resources