I have a function which is triggered on every mouse-down event when the mouse pointer is over the image.
Now, I call two functions in this mouse-down function.
I need one function Triangulate() be called every time and the other one ImageCalculation() last time only.
Here last time only means, a gap of minimum 3 seconds or more should be there between consecutive img_mouse_down() function calls.
Below is my code:
function img_mouse_down(){
if(leftMouseButton){
Triangulate(); //Call this function every time.
ImageCalculation(); //Call this function only the last time
}
}
If I click over the image 5 times continuously and then pauses for 3 or more seconds, Triangulate() should be called 5 times and the ImageCalculation() should be called only once.
How to achieve this?
var glob_timeout_holder;
function img_mouse_down(){
if(leftMouseButton){
Triangulate(); //Call this function every time.
clearTimeout(glob_timeout_holder); //clear if any previous continuing timeouts
glob_timeout_holder = setTimeout(ImageCalculationlast, 3000);
}
}
This may help you, as far as I understood. Everytime img_mouse_down() run, it will set a timeout to execute ImageCalculation(), but just before that kill any previous timeOuts, result is, if user stop clicking, ImageCalculation() will be called once 3 seconds after last click.
Something like that should address your problem. The timeout is cleared on every call and otherwise ImageCalculation is triggered after 3 seconds.
var timer = null
function img_mouse_down () {
if(leftMouseButton){
Triangulate();
if (timer !== null) {
clearTimeout(timer)
}
timer = setTimeout(function () {
ImageCalculation()
}, 3000)
}
}
Related
I've been trying to create an object which moves up and, after three seconds, comes back down, but I can only find code which tracks how long it takes until the command executes (ex. setInterval), rather than how long the code actually runs. Does anyone know how you'd bring the object back down after a specified time interval?
addEventListener("keyup", () => {
char.style.transition = "0.3s ease";
char.style.transform = "translateY(50%)";
});
setTimeout(function(){
alert("bring down object");
//function that brings out object goes here
}, 3000);
3000 is the amount of time to wait before running the function its default is in milliseconds so here it waits for 3 seconds before running the function manipulate that number to fit your required wait time before running the function that brings back the object.
I want to call a function that could check an amount of time constantly using an interval within function that already works (running function) by interval.
That what I had did:
var interval;
var time = prompt("Insert amount of time in seconds");
function log ()
{
console.log ("log() called.");
}
function onrunning ()
{
interval = setInterval(log,time*1000);
}
gameloop = setInterval(onrunning,5);//This interval must not cleared
The first amount of time works fine but after that it's keep calling the log() function faster and faster till the browser crashes.
I tried to do this
var interval;
var time = prompt("Insert amount of time in seconds");
function log ()
{
console.log ("log() called.");
}
function onrunning ()
{
interval = setInterval(log,time*1000);
}
gameloop = setInterval(onrunning,5);
clearInterval(interval); //tried this but no differece.
You are clearing interval in a wrong place.
In your code, you are trying to clear it before it has been created (so it's basically a no-op).
You want to clear it after it has been created and executed:
function log ()
{
console.log ("log() called.");
clearInterval(interval);
}
You should also notice that since your onrunning is also fired as an "interval" callback, you are creating new log intervals on each callback execution frame. If you want to clear this interval too, just replicate the same logic as presented above, but inside onrunning callback.
I assume you want to fire the "log" callback ("onrunning" callback as well, probably) only once after a set period of time. In that case, you should use setTimeout instead of setInterval.
This has been already pointed out by Jaromanda X in this comment.
I am trying to understand this code:
function setIdle(cb, seconds) {
var timer;
var interval = seconds * 1000;
function refresh() {
clearInterval(timer);
timer = setTimeout(cb, interval);
};
$(document).on('keypress, click', refresh);
refresh();
}
setIdle(function() {
location.href = location.href;
}, 5);
setIdle takes two arguments. Inside its function it has a function refresh that clears a timer on a Timeout function. Now every time when an event happens (click, keypress) refresh() gets called.
and then finally this function gets called passing in another function and and int value (5) which later will be the amount of seconds for the timer. In that other function which later is represented through cb the page will be refreshed (location.href = location.href;).
This causes an automaticpage refresh every 5 seconds.
So now I don't understand if I put an additional function:
setIdle(function() {
console.log('hi');
}, 1);
Why is the second function only called once and not every second like the other one?
setIdle doesn't run the callback function every 5 seconds. It runs it once, 5 seconds after you call setIdle, and if you type or click something the timeout gets pushed back again. So it runs it once, when you've been idle for 5 seconds.
The reason the page refreshes every 5 seconds is because the callback function reloads the page, and reloading the page runs all the Javascript in the page again, so that calls setIdle() again.
But your second use of setIdle doesn't reload the page, so it just logs hi once.
If you want to do something repeatedly every N seconds, use setInterval rather than setTimeout.
BTW, clearInterval should be clearTimeout. In most browser they're currently interchangeable, but there's no guarantee. See Are clearTimeout and clearInterval the same?
I'm not 100% sure how setTimeout works in JavaScript. Say I have something like this:
$(document).ready(function() {
testTimeout();
});
function testTimeout() {
alert("testing timeout");
setTimeout(testTimeout, 5000);
}
This would display a popup window every 5 after the page is ready. What would happen if then I called testTimeout from a button click?
$("#button").click(function() {
testTimeout();
});
Would the button click call testTimeout and add another timeout every 5 seconds? Or, would the button click reset the timeout from when the button was pressed? The reason I am asking is because I would like to design something like this where I can pass a parameter to my timeout function. When the web page starts up, I have a default parameter. However, if I press a button, I would like my timeout function to be called right away and every 5 seconds after with my new parameter. But, I don't want the timeout function with the old parameter to continue repeating. How can I achieve this? Any help and understanding would be greatly appreciated.
This would display a popup window every 5 after the page is ready.
No it wouldn't, it would show an alert repeatedly with no delay and/or cause a "too much recursion" error, because setTimeout(testTimeout(), 5000) calls testTimeout and passes its return value into setTimeout, just like foo(bar()) calls bar and passes its return value into foo.
If you remove the ():
function testTimeout() {
alert("testing timeout");
setTimeout(testTimeout, 5000);
// here --------------^
}
Then it would do that.
What would happen if then I called testTimeout from a button click?
You'd end up with the function being called twice as often (more than once every 5 seconds), because every time you call it, it reschedules itself. A third time would make it more frequently still (three times/second), and so on.
If you want to avoid that, one option is to remember the timer handle and cancel any outstanding timed callback if you call the function before then:
var handle = 0;
function testTimeout() {
clearTimeout(handle); // Clears the timed call if we're being called beforehand
alert("testing timeout");
handle = setTimeout(testTimeout, 5000);
}
(I initialized handle with 0 because calling clearTimeout with a 0 is a no-op.)
Have you tried to asign variable to your setinterval;
var foo = setTimeout(testTimeout(), 5000);
and then when right event comes just destroy that variable.
clearInterval(foo);
And now you can asign it again...
In your case it would simply repeat endlessly, because you're executing the function instead of passing the reference. You should do it like this:
function testTimeout() {
alert("testing timeout)";
setTimeout(testTimeout, 5000);
}
Note the missing braces after testTimeout. This tells setTimeout to execute that function, instead of the result of that function, which is how your original code behaved.
" I would like my timeout function to be called right away and every 5 seconds after with my new parameter. But, I don't want the timeout function with the old parameter to continue repeating "
In order to achieve what you're trying to do you should remove the timeout:
var timeoutId;
function testTimeout() {
alert("testing timeout)";
clearTimeout(timeoutId );
timeoutId = setTimeout(testTimeout, 5000);
}
Notes:
You can stop the previous timeoutI from firing by catching the id returned from the setTimeout method and passing that to the clearTimeout method
I want to schedule events, that will fire and call my predefined callback
How can schedule in js / jquery:
one time event?
recurring event (to call my function every minute, or five minutes)?
You want setTimeout for a one time event and setInterval for a repeating event.
Both take two arguments: a function and an interval of time specified in milliseconds.
var delay_millis = 1500;
//will alert once, at least half a second after the call to setTimeout
var onceHandle = window.setTimeout(function() {
alert("Time has passed!");
}, delay_millis);
//will alert again and again
var repeatHandle = window.setInterval(function() {
alert("Am I annoying you yet?");
}, delay_millis);
Bonus: if you keep around the values returned by calling these functions, you can cancel the callback if you need to.
var shutUpShutUp = function() {
window.clearInterval(repeatHandle);
};
shutUpShutUp(); //now I can hear myself think.
jQuery has nothing to do with it. You need JavaScript timers: setTimeout() and setInterval()
A one-time event is just scheduled with a setTimeout call. An easy way for a recurring event is to simply call setTimeout in the function that you are setting the timeout on.
The easiest way to schedule events (at predefined intervals) is window.setTimeout.
For a one time event, you set the timeout once and let the timeout fire.
For recurring events, you set the timeout once and then reset the timeout in the method that gets called.
You can bind a function to an event that will be run only once by using .one() in jQuery...
http://api.jquery.com/one/
For the problem of a timing threshold for an event, declare your event like this:
var clickAvailable = true;
$('#element').click(function(e) {
if(!clickAvailable) {
clickAvailable = false;
//your code
setTimeout(function() {
clickAvailable = true;
}, 5*60*1000); // 5 minutes...
}
});