I am trying to alter the code given here: http://jsbin.com/iFesOvOs/1/edit in such a way that a single button would both start and stop the timer.
If the timer is stopped, it will get started n press of the button and if it is running, it will be stopped.
I need to do this because I am making a mobile site with lot of features and we do not have space to place an additional button.
What I have tried:
I have tried altering some attribute of the button, so that we can detect if the timer is running or not and take action as per that.
I have tried storing the timer's state in localStorage, fetch it back up and take action as per that.
I have tried keeping a global variable, but that too didn't work
Sometimes, the desired function didn't get executed at all (with no error messages) and sometimes, I got the error message of variables going out of scope - which I tried to rectify by use of global variables but only in vain.
What's wrong here, can someone help me out?
This works...
<input type="button" value="start" onclick="start(this);">
function start(b) {
if (b.value == 'stop'){
b.value = 'start'
clearInterval(clocktimer);
return
}
b.value = 'stop'
clocktimer = setInterval("update()", 1);
x.start();
}
You can add class with name (start) to your button, add function that check if the class button name is start then start the trimer and change the button class name to stop, else when the class name is stop then stop the timer and change the class name to start.
Related
For example: In my Google Spreadsheets document there is a timer with a start and stop button. So far everything works. But if someone clicks on the 'stop' button by mistake although the timer is currently not running, it will causes issues and let the timer display a large and incorrect time. So I'm searching for methods to gray out the 'stop' button until 'start' was pressed. After, 'start' should be grayed out and 'stop' now available.
Has anybody ideas?
And then there's that I'm a total beginner in terms of scripting so the best bet would be if someone could help me out with the the script code.
Best method to prevent a script to run in parallel is to use the Lock Service.
When your button is pressed, you run a method that will acquire a lock and release it when finished. If you happen to click the button while previous task is still running, the lock acquire will fail and you can for example show an alert or just ignore the error.
function onButtonClick(){
const lock = LockService.getDocumentLock()
try{
lock.waitLock(1000)
// do some work
} catch(e){
if(e.message.indexOf('Lock')>=0){
SpreadsheetApp.getUi().alert(e.message)
}
} finally{
lock.releaseLock()
}
}
There is a method in Class Sheet call getDrawings() which returns all of the drawings on a sheet and that reveals the Class Drawing which has methods that allow you to reset the macro so you could set it to a dummy macro that doesn't do anything which should in effect disable the button.
If I have a online shopping platform, I want to call my REST API after the user stops clicking the add button.
Let's say that he wants 10 products, and he starts clicking the "add" button. I don't want to make a call every time the user presses the "add" button. I want to know when the user stops clicking and then make a call to my server with the quantity = 10.
btw I'm using Angular2.
Add setTimeout(backendCallback, ms) on each click. If clicked again - clear timeout and repeat.
let timer;
let callbackDealy = 800;
onAddClick(){
clearTimeout(timer);
timer = setTimeout(() => {
this.http.get().subscribe(...);
}, callbackDelay);
}
I'm not sure you can reliably predict the end of user interaction in this manner, but that aside, you could do something like this:
var cancelToken;
$("#myButton").click(() => {
cancelToken && clearTimeout(cancelToken);
cancelToken = setTimeout(() => {
alert("5 seconds elapsed")
}, 5000);
});
Clicking the button sets a timer that is cancelled & renewed each time the button is clicked.
Fiddle: https://jsfiddle.net/oop5wyxL/3/
You can use (click) event handler and use a timeout to do the call. When a click is done, you reset the counter. So, you can set the counter to the time you think is correct to ensure the user stopped clicking. Something like this:
html
<button (click)="saveBasket()">
js
timer;
saveBasket(){
if (this.timer) { // RESET THE TIMER IN EVERY CLICK
clearTimeout(this.timer);
this.timer = null;
}
timer = setTimeout(callAPI(), 10000); // CALL THE API AFTER 10 SECONDS
}
The idea you're describing is similar to debouncing; but this isn't a typical use case for such an approach.
Well, if you really want to do it, I suppose you could use a timeout. So in the handler for clicking on Add, set a timeout that waits a short time and then sends the request to the server. (Before setting the timeout for this click, remember to cancel any timeouts from previous clicks or it's all for naught.) But then you also have to watch out for the user navigating away before the timeout expires...
In an angular app, why should a quantity change require a server call anyway? Isn't there something like "submit order" that the user will click once all quantities are set? Is the server call just so the server can recalculate a price to display? If so, do that client-side; that's why you use angular.
I'm new to JavaScript.
I'm writing a simple code to add it in a chrome extension call it Shortkeys.
I just want the code to make a simple action:
Wait for a click of the mouse and then click a button in certain positions of the screen after 500 ms...
This is what I have written until this moment but is not working:
document.addEventListener('click', TimerThenPlay);
function TimerThenPlay(e) {
setTimeout(500)
document.elementFromPoint(1175, 85).click();
stop(TimerThenPlay);
clearTimeout(TimerThenPlay);
return;
};
What I'm doing wrong?
EDIT:
I have an APP running on Chrome...
I need to Click a Link and wait 500 ms to click a button... i can do that manually but sometimes dsnt work and i have to try again..
I realize that chrome has an extension that you can inject to the page a javascript code when u press a key in your keyboard. Thats why im using Shorkeys (if u know a better extension for this, just tell me).
Well... i have assign the < key to run the code...
What i need, is that everytime that i hit the < key... Chrome waits for a click (so i have time to look for the link that i want to open with de button)...
And when i click the link, it waits 500 ms and then click the button in the position that i select ( i cant use the Button ID cause it changes every minute).
I have tried the codes above and it works for the first time.. then, i dnt know why is keeping clicking 500 ms after a make a mouse click in the next pages... How can i stop that loop in the next page?
function TimerThenPlay(e) {
setTimeout(function(){
document.elementFromPoint(1175, 85).click();
stop(TimerThenPlay);
clearTimeout(TimerThenPlay);
},500)
}
SetTimeout method takes two arguments. First is function to execute after second argument time passes.
Hope this helps
Your setTimeout syntax is wrong.
Syntax of setTimeout:
setTimeout(function(){}, time)
you need to update your setTimeout function
function TimerThenPlay(e) {
setTimeout(function(){
document.elementFromPoint(1175, 85).click();
stop(TimerThenPlay);
clearTimeout(TimerThenPlay);
return;
},500)
};
I have a simple javascript program that runs onclick of an image.
However, whenever I clicked the image, the page reloaded.
After a lot of debugging I found that the page doesn't reload until right as the script completes.
There are several setTimeouts in the code, but I noticed the page was reloading instantly. I even changed these timeouts to 15000 milliseconds, but it still reloads immediately.
I am using jquery, if it makes any difference.
I also want a different result from the program every time you click it, so that each time you click it a different script runs and a some text changes in a specific order. I did this by changing the onclick attribute of the images in each script to the name of the next script, so that script one would switch onclick to script two, and so on. I set a timeout on these switches so that one click doesn't race through every single script. script two isn't running, so that much works.
my code:
function getSounds() {
console.log("script. initiated");
$("#soundwebGetSoundDirections").html("Now, Wait until the file is done downloading and click below again.");
console.log("new message");
$("#soundwebGetSoundA").attr('href',"");
console.log("href eliminated");
setTimeout($("#soundwebGetSoundImg").attr('onclick','findFile()'),2000);
console.log("onclick to findFile()");
}
function findFile(){
console.log("FINDFILE")
$("#soundwebGetSoundDirections").html("Find the file(it's probably in your downloads), copy the path of the file (usually at the top of the file explorer) and paste in it the box below. Then, make sure there is a '/' at the end of the path and type 'Linkiness.txt' (case sensitive, without quotes) at the end. Once you have all that stuff typed, click the icon again.");
console.log("FIND IT, DARN IT!!");
$("#soundwebGetSoundPathInput").css("opacity",1);
console.log("diving into reader");
setTimeout($("#soundwebGetSoundImg").attr('onclick','readFile()'),1000);
}
function readFile(){
console.log("loading...");
$("#soundwebGetSoundDirections").html("loading...");
if(document.getElementById("soundwebGetSoundPathInput").value.length == 0){
setTimeout($("#soundwebGetSoundDirections").html("Please fill in Path!"),1000);
setTimeout(findFile(),2000);
}
}
and the HTML that's linked to,
<a id = "soundwebGetSoundA" href = "https://docs.google.com/feeds/download/documents/export/Export?id=1ynhHZihlL241FNZEar6ibzEdhHcWJ1qXKaxMUKM-DpE&exportFormat=txt">
<img onclick = "getSounds();" class = "soundwebImgResize" src = "https://cdn3.iconfinder.com/data/icons/glypho-music-and-sound/64/music-note-sound-circle-512.png" id = "soundwebGetSoundImg"/>
</a>
Thanks for any help,
Lucas N.
If you don't want clicking the image to cause the anchor tag to load the href, then move the image tag outside of the anchor tag.
You aren't using setTimeout correctly. You should be passing in a function not a statement. So, for example, instead of
setTimeout($("#soundwebGetSoundDirections").html("Please fill in Path!"),1000);
setTimeout(findFile(),2000);
you should use
setTimeout(function () { $("#soundwebGetSoundDirections").html("Please fill in Path!") },1000);
setTimeout(findFile,2000);
I think the same goes for setting the onclick attribute but I've never tried dynamically changing an onclick attribute like that.
Since you're already using jQuery you could try using .on('click'... and .off('click'... if your current setup isn't working.
I'm using RadScheduler for my project. In the scheduler, I need a periodical update, so in my javascript, I set interval for a method that call rebind() on the RadScheduler for every 60 seconds. The problem is that, when my user open the advanced form, the rebind() method makes the form disappear. How can I detect AdvancedForm opening and closing event so that I can stop /restart the timer ?
Thank you in advance.
While there is an event for when the RadScheduler opens its Edit form, called OnClientFormCreated, there is not one for when the edit form closes. There are ways to do this though, but you have do add some additional code.
When you think about it there are several different items that can lead to the form closing - the user can click on the close icon at the top right (or left, depending on your orientation) of the window, they can click cancel, or they can hit save.
Keeping that in mind, we can take a look at this demo, which shows the Advanced Edit Form in action, and also has some JavaScript pre-written for us.
Within the schedulerFormCreated() function we can do the following:
function schedulerFormCreated(scheduler, eventArgs) {
// Create a client-side object only for the advanced templates
var mode = eventArgs.get_mode();
if (mode == Telerik.Web.UI.SchedulerFormMode.AdvancedInsert ||
mode == Telerik.Web.UI.SchedulerFormMode.AdvancedEdit) {
// Initialize the client-side object for the advanced form
var formElement = eventArgs.get_formElement();
var cancelButton = $("[id$='_CancelButton']");
cancelButton.on("click", formClosed);
var templateKey = scheduler.get_id() + "_" + mode;
....
And then we have the formClosed event:
function formClosed(eventArgs) {
}
in formClosed you can just create your logic for resuming the timer, while in schedulerFormCreated you can directly call the function that stops the timer right after that if-statement.
In case you're wondering what we're doing here we're simply grabbing an instance of the jQuery object representing the element with an id that ends with _CancelButton (we're not interested in the beginning part) and then just binding to the click event using the .on() jQuery function.
To get an instance of the save button you just have to use _UpdateButton, and for the close icon it is _AdvancedEditCloseButton. Keep in mind that any element that ends with these substrings will be selected, so if you want to be more specific I recommend inspecting the elements of your advanced form using FireBug or the Chrome Dev tools to get their ID and plug that into the selector above.
This should allow you to get the functionality you're looking for.