Execute javascript function every second while the button is pressed [duplicate] - javascript

This question already has answers here:
JavaScript while mousedown
(3 answers)
Closed 4 years ago.
I need to execute a javascript function continuosly (every second or half a second for example), but this needs to happen while a button is pressed.
I tried with the following:
$("#buttonID").bind('touchstart',function(event){
setInterval(function() {
FUNCTION
}, 1000);
});
It is not working that way, using "mousedown" either.
What it's answered on question JavaScript while mousedown
did not solve my issue, so I don't consider this question as a duplicate.
Is there a beginner's mistake and I'm not seeing it? what do you suggest?

You have to capture a reference to the timer and cancel it when the mouse is released.
var timer = null; // Will hold a reference to the timer
$("#buttonID").on('mousedown',function(event){
// Set the timer reference
timer = setInterval(function() {
console.log("Function running");
}, 1000);
});
$("#buttonID").on('mouseup',function(event){
clearInterval(timer); // Cancel the timer
console.log("Timer cancelled.");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="buttonID">Hold me down to run function!</button>

Related

How to load Bootstrap Modal in the presence of a javascript function that reloads the page every second? [duplicate]

This question already has answers here:
How do I clear this setInterval inside a function?
(4 answers)
Calling a function on Bootstrap modal open
(6 answers)
How can I call a function when a Bootstrap modal is open?
(2 answers)
Closed 11 months ago.
I use Bootstrap 4.7 Modal on a page. This page also has a javascript function that reloads the page every second, e.g.,
setInterval(function () {
somefunction();
}, 1000);
The problem is that the Modal doesn't work. I guess it doesn't because the moment it pops up the page has to reload so it fails. Then I believe I need to tell setInterval to stop reloading if Modal is active? Is there an easy way around this? Thanks a lot
If you save the interval as a variable, you can stop it later hen a button is clicked (for example).
var myTimer = setInterval(function () {
somefunction();
}, 1000);
Now just call clearInterval(myTimer) to stop it.
Or, let's really simplify it like this.
var myTimer = null;
function startTimer() {
myTimer = setInterval(function () {
somefunction();
}, 1000);
}
function stopTimer() {
clearInterval(myTimer);
}
Now you just need to call startTimer() and stopTimer()

How to make functions get called sequentially in JS? [duplicate]

This question already has answers here:
Wait until setInterval() is done
(6 answers)
Closed 2 years ago.
I am making a webpage where once the user clicks on the start button, some changes will happen to the CSS of the page (I wrote the required JavaScript (JS) code). Only after these changes happen, I want some other changes to happen. In an attempt to achieve this, I wrote calls to 2 functions inside the function that gets called once the event happens: (In the below JS code, the 2 functions begin called inside the function that which gets triggered by the "click" event are- startCountdown and showWords)
document.getElementById("startButton").addEventListener("click",startTheGame);
function startTheGame()
{
var contentSlides = document.getElementsByClassName("slide");
// Game started so we are hiding the start slide!
contentSlides[0].classList.add("hideDisplay");
//
// Now the "321 Go!" down timer is to be shown!
contentSlides[1].classList.remove("hideDisplay");
startCountdown(document.getElementById("onClickCount"));
showWords();
//
}
function startCountdown(reqElement)
{
var time = 2;
var intervalId = setInterval(function ()
{
reqElement.innerText = time;
if(time==="Go!")
clearInterval(intervalId);
time-=1;
if(time===0)
time = "Go!";
},1000);
}
function showWords()
{
alert("Hi!");
}
In the showWords function also, I wish to make some changes to the page. But, I want it to get executed only after the startCountdown function gets executed completely. As of now when I am running the above code, as soon as I click on the button, the alert is popping up! - But I don't want it to happen.
What changes do I need to make?
(After the showWords function gets executed completely - I want one more function to be executed - in this way I want the functions to be executed sequentially - i.e. the changes must happen in a specific order.)
Thanks for the help!
P.S.: Please let me know if you aren't able to understand my question.
so when it's called clearInterval like this
document.getElementById("startButton").addEventListener("click",startTheGame);
function startTheGame()
{
var contentSlides = document.getElementsByClassName("slide");
// Game started so we are hiding the start slide!
contentSlides[0].classList.add("hideDisplay");
//
// Now the "321 Go!" down timer is to be shown!
contentSlides[1].classList.remove("hideDisplay");
startCountdown(document.getElementById("onClickCount")); //
}
function startCountdown(reqElement)
{
var time = 2;
var intervalId = setInterval(function ()
{
reqElement.innerText = time;
if(time === 0){
clearInterval(intervalId);
reqElement.innerText = "Go!"
showWords();
}
time--;
},1000);
}
function showWords()
{
alert("Hi!");
}

HTML5 Canvas – Stop previous requestAnimationFrame [duplicate]

This question already has an answer here:
How do I stop requestAnimationFrame
(1 answer)
Closed 6 years ago.
I'm using HTML Canvas. I want new frames to be requested only if the click function hasn't been fired again. Basically I want it to "stop" the previous recursiveness, I think
document.addEventListener('click', function(){
[...]
var animate = function() {
if (the click event was NOT fired again) {
requestAnimationFrame(animate);
}
};
animate();
});
How would I do this?
You can set a global variable like rafId and in the line you invoke rAF make it like;
rafId = requestAnimationFrame(animate);
then when needed invoke cancelAnimationFrame() like cancelAnimationFrame(rafId)

Delaying javascript function execution [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I am using jQuery(Latest release) and have a function called "calculate()" which gets called every time a field is edited and the field exited(blur etc). (To allow "dynamic" calculation")
The calculation takes under 4 seconds to complete, but if the user changes another element on the form before the calculation is complete, then they are queued and the function is called again after the current action is complete.
As I can't stop the function from processing once it's started, is it possible to delay the function by a couple of seconds and then each time a form element is interacted with, add to the timer.
I don't think this is possible, but thoguht i'd give it a shot.
I know I could do:
setTimeout(function(){ ... }, 4000);
but I would need a way to add to this timer. (i.e. The timer has 1 second left, I click on a field and I want the timer to go back to 4 seconds)
What I would do is something like this:
var isCalculating = false;
var calculateQueue = false;
function calculate(){
isCalculating = true;
// do calculations
isCalculating = false;
if(calculateQueue){
calculate();
}
}
$('element').blur(function(){
if(!isCalculating){
calculate();
}
else{
calculateQueue = true;
}
});
This way you don't run concurrent calculate() functions. No need for endless timers, and if there are calculations "queued" then they will be calculated after the first calculate function stops... rather than waiting 4s each time. What happens when you change your calculate function and it takes longer?
Hope this helps.
This can be handled by calling clearTimeout() before executing the setTimeout() to clear any pending actions.
// Declare the variable that holds the timeout pointer at a higher scope
var ts;
// in your onblur
// clear any pending pointer
if (ts) window.clearTimeout(ts);
// then reset the timeout and assign its handle to the same variable ts
ts = window.setTimeout(function() {}, 4000);
You problem is not to add to the timer, but to clear the previous timer.
You could do it like:
var delay = (function() {
var time_id;
return function(callback, ms) {
if (time_id) {
window.clearTimeout(time_id);
}
time_id = window.setTimeout(callback, ms);
};
}());
// use it like
delay(function(){...}, 4000);
You could remember the timeoutID and reset the old timer each time you start a new one.
var timeoutID = null;
if ( timeoutID !== null ) {
window.clearTimeout( timeoutID );
}
timeoutID = window.setTimeout( function(){
// your code here
}, 4000 );
As others have mentioned, clearTimeout is the way to handle this. I put together a really basic example of how this works. A click on the button will cancel and restart the timer before the function runs, but this event could easily be bound to another event (like a focus or blur on a field, like it looks like you would be doing)
Example of delaying execution with clearTimeout here >>

How to pause a setTimeout call? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
javascript: pause setTimeout();
Im using jQuery and working on a notification system for my site. The notifications automatically fadeout using the setTimeout function.
How can i stop the timer of the setTimeout call?
For example i would like to pause the setTimeout call while the mouse is over the notification and continue the count down mouseout...
I googled "pause setTimeout" with no luck.
Im currently clearing the setTimeout call with clearTimeout and at same time fading out the notification on mouseout but it would be nice to have that pause effect.
Any ideas?
Try this.
var myTimeOut;
$(someElement).mouseout( function () {
myTimeOut = setTimeout("mytimeoutfunction()", 5000)
});
$(someElement).mouseover( function () {
clearTimeout(myTimeOut);
});
It wouldn't be too hard to add a PausableTimeout class:
(Might not be valid JS, but it shouldn't be too hard to get it working):
function PausableTimeout(func, millisec) {
this.func = func;
this.stTime = new Date().valueOf();
this.timeout = setTimeout(func, millisec);
this.timeLeft = millisec;
}
function PausableTimer_pause() {
clearTimeout(self.timeout);
var timeRan = new Date().valueOf()-this.stTime;
this.timeLeft -= timeRan;
}
function PausableTimer_unpause() {
this.timeout = setTimeout(this.func, this.timeLeft);
this.stTime = new Date().valueOf();
}
PausableTimer.prototype.pause = PausableTimer_pause;
PausableTimer.prototype.unpause = PausableTimer_unpause;
//Usage:
myTimer = new PausableTimer(function(){alert("It works!");}, 2000);
myTimer.pause();
myTimer.unpause();
Of course, it'd be a great idea to add some error checking in there (don't want it to be possible to unpause the timeout multiple times and end up with hundreds of timeouts!), but I'll let that be your job :P
Use clearTimeout() on mouseover event and use setTimeout() again on mouseout event.
http://www.w3schools.com/jsref/met_win_cleartimeout.asp

Categories

Resources