Javascript click and hold on element using setTimeout - javascript

I need to have some functionality in my web app where a specific action occurs when the user clicks and holds on an element. Think of it like the long press on Android.
I have my div:
<div id="myDiv"
onmousedown="press()"
onmouseup="cancel()"
onmouseout="cancel()"
onmousemove="cancel()">Long Click Me</div>
and my javascript:
var down = false;
function press()
{
down = true;
setTimeout(function() { action(); }, 1500);
}
function cancel()
{
down = false; // this doesn't happen when user moves off div while holding mouse down!
}
function action()
{
if (!down)
return; // if the flag is FALSE then do nothing.
alert("Success!");
down = false;
}
This works as long as all I do is press and hold on the element. I have the onmouseout and onmousemove events to call cancel() because I want the user to have the option to change their mind and move the mouse off the element before action() starts.
Unfortunately, it seems that my code does not do this.
In fact, if the use clicks down for a moment, moves the mouse off the div and releases before the 1.5 sec then action() won't bail out as expected.
Edit: Thanks for your input everyone but it turns out I'm just a little bit special and didn't see that I forgot a capital letter in my HTML in my onmouseout. The sample code I gave above should work exactly as expected.

Of course action() is still called. You didn't actually cancel the setTimeout() function. I would suspect that maybe in your real code, you have a scoping issue and maybe aren't testing the same version of the done variable that you think you are.
A better way than using the down flag would be to keep track of the return value from setTimeout() and actually cancel the timer in the cancel() function. Then, action() will never fire when you don't want it to. I think it's also technically a more correct behavior when you mouseout to cancel any chance of the timer firing.
Also, there is no such thing as:
bool down = false;
in javascript. It would have to be:
var down = false;
I would recommend this code:
var downTimer = null;
function down()
{
cancel();
downTimer = setTimeout(function() { action(); }, 1500);
}
function cancel()
{
if (downTimer)
{
clearTimeout(downTimer);
downTimer = null;
}
}
function action()
{
downTimer = null;
alert("Success!");
}

You also need to clear the timeout in your cancel function - otherwise it will still fire - as you initiated it in the down function.
so..
bool down = false;
//your timeout var
var t;
function down()
{
down = true;
t = setTimeout(function() { action(); }, 1500);
}
function cancel()
{
down = false;
clearTimeout(t);
}
function action()
{
if (!down)
return;
alert("Success!");
down = false;
}

There are several things wrong with your code as I see it.
First
bool down = false;
is not valid JavaScript. It should be
var down = false;
Then you have two variables called down: the boolean value and the function. The function will overwrite the variable, until as such time that you execute one of the statements that sets down to true or false.
As others have said: once set, the deferred function will continue to be executed 1.5 seconds later, unless you cancel the timeout. But then again it doesn't matter, since you do check to see if the mouse button is down before doing anything.
So I'd say rename the boolean variable to isMouseDown or something and try again.

to cancel the timeout in the cancel() function, use
var mytimer = null;
function ondown(){mytimer = setTimeOut('action()', 1500;)}
function cancel(){clearTimeout(mytimer);}
function action(){mytimer=null; alert('success!');}
also note that you used down first as a variable end then as a function... Calling if(!down) will always return false because down refers to a function.

Related

Javascript sleep until key is pressed

I did some research and found busy wait solutions. I don't want the processor to execute a loop in the script until I get a keypress event through JQuery.
How can I pull of something like sleepUntilKeyPress(), which is a function like sleep() in C but instead of waiting some especific time it waits for a keypress?
You're thinking backwards. Your function shouldn't wait for a keypress to do something, the function should do something whenever a key is pressed. Maintain your data state in a scope that your key callback can reach and update your state on keypress.
You're trying to say:
while(!keypress){
dontDoSomething();
}
You should be doing something more like:
on(keypress, doSomething);
Consider this idea:
var counter, ispressed, el;
// Bad
counter = 0;
ispressed = false;
el = document.getElementById("element");
el.addEventListener("mousedown", function () {
ispressed = true;
});
el.addEventListener("mouseup", function () {
ispressed = false;
});
while (1) {
if (ispressed) {
counter += 1;
}
}
// Better
el.addEventListener("click", function () {
counter += 1;
});
Let's forget about the fact that that while will lock up the program, (I don't even think the event listeners will trigger and I'm pretty sure the DOM will lock up), you're asking your program to waste time constantly checking to see if you're pressed a button yet. Rather than do that, let the browser check for you with the built in addEventListener() and do what you would normally do when you find out that the button has been pressed.
var interval = window.setInterval(function () {
// hang around and do nothing
}, 1000);
document.onkeypress = function () {
if (/* some specific character was pressed */) {
window.clearInterval(interval);
// do some other thing, other thing
}
};

Stopping current operation and proceed to another (new) operation

function windowResize() {
someFunction();
console.log("test3");
}
function someFunction(){
console.log("test");
longExecutingFunctionWithAsyncReq();
console.log("test2");
}
function longExecutingFunctionWithAsyncReq() {
// some codes here
}
whenever the window is resize(zoomed out/in), this function is called.
But if the user spams the zoom, someFunction() will not have the time to finish and will then cause the error.
I'm thinking of addressing this issue by stopping the current operation and then process the new operation. Also, I've tried reading about Deferred and Promise, but I can't grasp the simplicity of the topic and I'm not sure if it really solves my problem. Plus, I've also checked on callbacks and was very doubtful that this will not solve my problem either.
If my solution is not possible though, I thought of just queuing the operations, but the downside might be, the queue might overflow if not controlled. As for this solution, I've not looked any farther to this, except reading about it.
you could use a timeout and clear it before resetting it when the resize function is called:
var myTimeout;
function windowResize() {
clearTimeout(myTimeout);
myTimeout = setTimeout(someFunction, 500);
}
this way the function will be called when the user stops resizing and 500 miliseconds have passed.
if you just need to wait for operation to finish you can set up a flag.
var working = false;
function windowResize() {
if (!working){
working = true;
someFunction();
console.log("test3");
}
}
function someFunction(){
console.log("test");
longExecutingFunctionWithAsyncReq();
console.log("test2");
}
function longExecutingFunctionWithAsyncReq() {
// some codes here
// on finish set working to False
}
var isStillWorking = false;
function windowResize() {
if(isStillWorking) {
// Do nothing.
} else {
someFunction(function(){
isStillWorking = false;
});
console.log("test3");
}
}
function someFunction(callback){
isStillWorking = true;
console.log("test");
longExecutingFunctionWithAsyncReq();
console.log("test2");
}
function longExecutingFunctionWithAsyncReq() {
// some codes here
}
To clarify more of Anton's answer I manage to implement the same thing using a flag [global] variable and a callback. I use a callback in order to flag=false since I also need to wait for the asynchronous requests inside the function to finish before resetting the flag.

How to make part of a function only execute once until it's allowed to do otherwise

How can I call a javascript function (repeatedFunction()) repeatedly but make it so that, let's say an alert("This function is being executed for the first time"), is only activated the first time that repeatedFunction() is, but the //other code is always activated? And also, how can I make the alert() allowed to be activated for one more time, like if the repeatedFunction() was being executed for the first time again?
You can set a flag. Say for example, you have this following code:
var flagAlertExecd = false;
function repeatThis () {
if (!flagAlertExecd) {
alert("Only once...");
flagAlertExecd = true;
}
// Repeating code.
}
And to repeat this code, it is good to use setInterval.
setInterval(repeatThis, 1000);
Functions are objects. You can set (and later clear) a flag on the function if you like:
function repeatedFunction() {
if (!repeatedFunction.suppress) {
alert("This function is being executed for the first time");
repeatedFunction.suppress = true;
}
// ...other code here...
}
When you want to reset that, any code with access to repeatedFunction can clear the repeatedFunction.suppress flag:
repeatedFunction.suppress = false;
The flag doesn't have to be on the function, of course, you could use a separate variable.
That said, I would suggest looking at the larger picture and examining whether the alert in question should really be part of the function at all.
JavaScript closure approach will fit in this task. It has no global variables, and keeps your task in a single function.
var closureFunc = function(){
var numberOfCalls = 0;
return function(){
if(numberOfCalls===0)
{
console.log('first run');
}
numberOfCalls++;
console.log(numberOfCalls);
};
};
var a = closureFunc(); //0
a(); //1
a(); //2
var a = closureFunc(); //drop numberOfCalls to 0
a(); //1
http://jsfiddle.net/hmkuchhn/
You can do it by declaring a variable and incrementing it in your function. Using an if statement, you can check how many times it has been triggered. Code :
var count = 0;
function myfunc(){
if(count==0){
alert("Triggering for the first time");
count++;
}
//Your always triggering code here
}
Demo
This even tracks record of the how many times the function is triggered. It can be useful if you don't want to execute the alert() on nth time.
You can also use boolean values. Like this :
var firstTime = true;
function myfunc(){
if(firstTime){
alert("Triggering for the first time");
firstTime = false;
}
//Your always triggering code here
}
Demo
The second approach will not track the record of how many times the function has been triggered, it will just determine that whether the function is being invoked for the first time or not.
Both the approaches work fine for your purpose.
var firstTime = true;
var myFunction = function() {
if(firstTime) {
alert("This function is being executed for the first time");
firstTime=false;
}else{
//whatever you want to do...
}
}; //firstTime will be true for the first time, after then it will be false
var milliseconds = 1000;
setInterval(myFunction, milliseconds);
//the setInterval means that myFunction is repeated every 1000 milliseconds, ie 1 second.

How to clear a javascript timeout thats set within a function

I have a recursive type function in Javascript that runs like this:
function loadThumb(thumb) {
rotate=setTimeout(function() {
loadThumb(next);
}, delay);
}
Note: I've simplified the function to make it easier to read.
I have "a" tags called like this
Load thumb 3
However, they don't clearout the timer, the timer continues to cycle through the function irregardless of the clearTimeout() being called.
Any ideas why? I think it might have something to do with a scope problem or something like that.
Yeah, you need to make rotate a global variable. Simply declare it outside the function like so:
var rotate;
var delay = 1000;
function loadThumb(thumb) {
alert("loading thumb: " + thumb);
rotate = setTimeout(function() {
loadThumb(thumb + 1);
}, delay);
}
Also, you need to make sure you clear the timeout before you call loadThumb. Otherwise you'll clear the timer you just started.
Load thumb 3
fiddle: http://jsfiddle.net/63FUD/
it may be the issue of scope so make rotate as global variable and call clearTimeout(rotate);
refer clearTimeout() example
It may be a scoping issue if you are not declaring rotate externally.
Try this:
var rotate = 0;
function loadThumb(thumb) {
rotate=setTimeout(function() {
loadThumb(next);
}, delay);
}
Return false on the link
Since you are not using var rotate, it should not be a scoping issue since rotate would be in the window scope. Can you show the complete code?
It is considered poor coding to inline the script - you should attach the event handler onload of the page
Also you should not have the setTimeout inside a function that might be called for one image
Try this:
var rotate,next=1;
function loadThumb(thumb) {
if (thumb) ... use thumb
else ... use next
}
function slide() {
rotate=setInterval(function() {
loadThumb();
next++;
if (next>=images.length) next=0;
}, delay);
}
window.onload=function() {
var links = document.getElementsByTagName("a");
if (links[i].className==="thumbLink") {
links[i].onclick=function() {
var idx = this.id.replace("link","");
loadThumb(idx);
clearInterval(rotate);
return false;
}
}
document.getElementById("start").onclick=function() {
slide();
return false;
}
document.getElementById("stop").onclick=function() {
clearInterval(rotate);
return false;
}
slide();
}
assuming
Start
Stop
Show 1
Show 2
Show 3
If you have to manage multiple timeouts, you can use an object in the global scope and some custom methods to create and remove your timeouts. To access the methods you can either put the calls in the onclick handler of your links (like in the example), or use a library like jQuery to bind them.
<script type="text/javascript">
var timeouts = timeouts || {};
function createTimeout(name, milliseconds, callback) {
timeouts.name = setTimeout(callback, milliseconds);
}
function removeTimeout(name) {
if (typeof(timeouts.name) !== undefined) {
clearTimeout(timeouts.name);
timeouts.name = undefined;
}
}
createTimeout('foo', 5000, function() {
alert('timeout')
});
</script>
i have also posted an example on jsFiddle http://jsfiddle.net/AGpzs/
I'm not sure what exactly you are doing, because as far as I can see you didn't post all the code, but this looks better for me:
function loadThumb(thumb) {
return setTimeout(function() {
loadThumb(next);
}, delay);
}
and then:
Load thumb 3

How to delay a function from returning until after clicks have occurred

The following confirmDialog function is called midway through another jquery function. When this confirmDialog returns true the other function is supposed to continue... but it doesn't. The reason for this seems to be that the entire confirmDialog function has already executed (returning false) by the time the continue button gets clicked. How can I delay it returning anything until after the buttons have been clicked?
(Or, if I'm completely on the wrong track, what is the problem and how do I fix it?)
function confirmDialog(message) {
....
$('input#continue', conf_dialog).click(function() {
$(this).unbind();
$('p',conf_dialog).fadeOut().text('Are you really sure you want to '+message).fadeIn();
$(this).click(function() {
$(conf_dialog).remove();
return true;
});
});
$('input#cancel', conf_dialog).click(function() {
$(conf_dialog).remove();
return false;
});
}
Im' not sure you can.
AFAIK only built-in function like confirm, alert or prompt can be blocking while asking for an answer.
The general workaround is to refactor your code to use callbacks (or use the built-in functions). So that would mean splitting your caller function in two, and executing the second part when the input is obtained.
In confirmDialog, you're setting up event handlers, that will execute when events are fired, not when confirmDialog is run. Another issue, is that you return true or false inside the event function, so that won't apply to the outer function confirmDialong.
The part that relies on the button presses would need to be re-factored. Perhaps put it in another function, and call it from the click handlers:
var afterConfirm = function(bool) {
if(bool) {
//continue clicked
} else {
//cancel clicked
}
//do for both cases here
}
//inside confirmDialog input#continue
$(this).click(function() {
$(conf_dialog).remove();
afterConfirm(true);
});
You may want to look into using Deferred objects. Here are two links that explain them.
http://www.sitepen.com/blog/2009/03/31/queued-demystifying-deferreds/
http://api.dojotoolkit.org/jsdoc/1.3/dojo.Deferred
Using a Deferred you could take your calling function:
function doSomething () {
// this functions does something before calling confirmDialog
if (confirmDialog) {
// handle ok
} else {
// handle cancel
}
// just to be difficult lets have more code here
}
and refactor it to something like this:
function doSomethingRefactored() {
// this functions does something before calling confirmDialog
var handleCancel = function() { /* handle cancel */};
var handleOk = function() { /* handle ok */};
var doAfter = function() { /* just to be difficult lets have more code here */};
var d = new dojo.deferred();
d.addBoth(handleOk, handleCancel);
d.addCallback(doAfter);
confirmDialog(message, d);
return d;
}
ConfirmDialog would have to be
updated to call d.callback() or
d.errback() instead of returning true
or false
if the function that calls
doSomething needs to wait for
doSomething to finish it can add its
own functions to the callback chain
Hope this helps... it will make a lot more sense after reading the sitepen article.
function callingFunction() {
$('a').click(function() {
confirmDialog('are you sure?', dialogConfirmed);
// the rest of the function is in dialogConfirmed so doesnt
// get run unless the confirm button is pressed
})
}
function dialogConfirmed() {
// put the rest of your function here
}
function confirmDialog(message, callback) {
...
$('input#continue', conf_dialog).click(function() {
callback()
$(conf_dialog).remove();
return false;
}),
$('input#cancel', conf_dialog).click(function() {
$(conf_dialog).remove();
return false;
})
...
}
You could add a timeout before the next function is called
http://www.w3schools.com/htmldom/met_win_settimeout.asp

Categories