Delaying a timed interval function? - javascript

I have a function set up like so:
setInterval(function () { get_fb(); }, 10000);
I'd like to reset the timer to 10 seconds whenever a user does something (like hover over an element or click an element)
How would I tell the program to do something like this?

Is you assign the timer to a variable you can clear it and restart it like this:
var timer = setInterval(get_fb, 10000);
$('#foo').click(function() {
clearInterval(timer); // stop timer
// do something...
timer = setInterval(get_fb, 10000); // restart timer
});

var timeout = setInterval(function () { get_fb(); }, 10000);
//to reset interval, first clear it
clearInterval(timeout);
//then re-create
timeout = setInterval(function () { get_fb(); }, 10000);

In the event callback, clear the interval, and then set the interval anew:
interval = setInterval(...);
...elsewhere...
$(..selector..).click(function () {
clearInterval(interval);
interval = setInterval(...);
});
Be sure that interval is accessible within the scope of the click callback.

Related

clearInterval() does not seem to work as expected

I am developing a JavaScript/WebRTC walkie-talkie app and require a button to be held down to send audio. It works fine until I click the right mouse button whilst holding the left which causes the setInterval function to continue working and clearInterval unable to stop it via its ID. It just continues on forever. According to everything I have read, clearInterval should stop it, especially if the interval is set globally.
var intervalId;
$("#transmitbutton").on("mousedown touchstart", function () {
intervalId = setInterval(function () {
console.log("PTT pressed");
}, 1000);
});
$("#transmitcontainer").on("mouseup touchend mouseleave", function () {
clearInterval(intervalId);
});
I have tried the start and stop buttons and it has the same outcome. clearInterval is not working.
var intervalId;
$("#transmitstart").on("click", function () {
intervalId = setInterval(function () {
console.log("PTT pressed");
}, 1000);
});
$("#transmitstop").on("click", function () {
clearInterval(intervalId);
});
If you happen to call your function that creates it more then one time you will have an interval that will not be cancelable since you will overwrite the interval id. So either you need to cancel it, or not make a new interval.
var intervalId;
$("#transmitbutton").on('mousedown touchstart', function() {
if (intervalId) return; // either exit out and not create a new one
// if (intervalId) clearInterval(intervalId); //or remove it here
intervalId = setInterval(function(){
console.log("PTT pressed");
}, 1000);
});
$("#transmitcontainer").on('mouseup touchend mouseleave', function() {
if (intervalId) clearInterval(intervalId);
intervalId = null;
});

How to change the interval dynamically when using setInterval

I have this fiddle : https://jsfiddle.net/reko91/stfnzoo4/
Im currently using Javascripts setInterval() to log a string to console.
What I want to do, is in this setInterval function check whether the interval variable has changed, if it has, change the interval in the setInterval function. I can lower the interval variable by 100 (speeding the function up) by a click a button.
Is this possible ?
Someone mentioned this : Changing the interval of SetInterval while it's running
But this is using a counter, so they only run it a certain amount of times. I need to run it for however long, but change how fast the function gets called again.
Here is the code :
var interval = 2000;
setInterval(function() {
interval = getInterval();
console.log('interval')
}, interval);
function getInterval() {
return interval;
}
$('#speedUp').on('click', function() {
interval -= 100;
console.log(interval)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='speedUp'>
speed up
</button>
I would just stop the interval and start a new one with the different timing
var interval = 2000;
var intervalId;
// store in a function so we can call it again
function startInterval(_interval) {
// Store the id of the interval so we can clear it later
intervalId = setInterval(function() {
console.log(_interval);
}, _interval);
}
function getInterval() {
return interval;
}
$('#speedUp').on('click', function() {
interval -= 100;
// clear the existing interval
clearInterval(intervalId);
// just start a new one
startInterval(interval);
console.log(interval)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='speedUp'>
speed up
</button>

Jquery setTimeout inside a setTimeinterval not working

I have a setinterval that moves bulldozer from the right to the left.
In the jsfiddle below, the setInterval must stop itself after 5 seconds. (used a settimeout and clearinterval for that) but it's not working. Can anyone help me?
http://jsfiddle.net/B5MKj/11/
var gameover;
gameover = setInterval(function () {
setTimeout(function () {
clearInterval(movingbulldozer);
}, 55000);
}, 10);
You had a typo in your fiddle, updated fiddle, if works just fine, but instead of 5000 ms you had 55000ms set for the timeout.
setTimeout(function () {
clearInterval(movingbulldozer);
}, 5000);
In your example, movingbulldozer is undefined. If you're trying to clear the interval, clear the interval with the right reference. In your example, this would be clearInterval(gameover);
The problem with your example is that every 10 ms you're adding a timeout to the DOM which clears the interval.
var timeout, interval, date,
i = 0;
$(document).ready(function() {
interval = setInterval(function() {
date = new Date();
i++;
$('#debug').html('Interval parsed at '+date.getTime()+', interval #'+i);
if (i >= 100) { // According to your example
$('#debug').html('Starting timeout...');
timeout = setTimeout(function() {
$('#debug').html('Timed out');
}, 5000);
clearInterval(interval);
}
}, 10);
});
Check out my example, see if it helps. :)
http://jsfiddle.net/faqq5/

starting and stopping a timer with jquery in hover

how would you guys reinitiate a javascript timer after it's been stopped. Basically I need the timer to stop, and then start again on rollout of a div. I have
var timer = setInterval(myFunction, 1000);
timer
function myFunction(){<br/>
if(){
do this
}
else if () {
do this
}
};
then I have
$("td").hover(
function () {
window.clearInterval()
},<br/>
function () {
timer
}
);
all works good except it doesn't start again on hover off. If I put a new timer in hover off the timer starts to speed up every time you hover on and off.... Any ideas.
Thanks
var intervalID = setInterval(myFunction, 1000);
function myFunction(){
//logic goes here
};
$("td").hover( function () {
window.clearInterval(intervalID)
},
function () {
intervalID = setInterval(myFunction, 1000);
} );
Explanation: What's happening is that the setInterval is returning the ID associated with that interval.
I did a littse jsFiddle to show it works.
NOTE: this doesn't pause the current Interval. It stops it and starts it again. So if you were in a 10sec interval at 9 secs and stopped it. When it starts again it will take another 10secs.

Implement a timer into js function

I have already this function I'm trying to add a timer like this: when value >= 1 and user doesn't move mouse for 1 minute or 60 seconds timer starts and redirect user to a new page but if user moves mouse before 60 seconds end the timer resets again.
function pagar(){
var textarea = document.getElementById ("textarea");
/*if (event.propertyName.toLowerCase () == "value") {
alert ("NUEVO VALOR EN EL CAMPO TOTAL: " + event.srcElement.value);
}*/
if (event.srcElement.value>=1)
{
var bottomMenu = $("#main_footer").bottomMenu([
{name:"backward","class":"red", text:getStr("menu_backward")},
{name:"menu","class":"green", text:getStr("menu_menu"), func:function(){parent.location = "./index.html";}, enabled:false},
{name:"forward","class":"green", text:getStr("menu_pay"), func:forward, enabled:true}
]);
}
else
{
var bottomMenu = $("#main_footer").bottomMenu([
{name:"backward","class":"red", text:getStr("menu_backward")},
{name:"menu","class":"green", text:getStr("menu_menu"), func:function() {parent.location = "./index.html";}, enabled:true},
{name:"forward","class":"green", text:getStr("menu_pay"), func:forward, enabled:false}
]);
}
}
I want to add a timer after this:
if (event.srcElement.value>=1)
{
You'll want to attach a mousemove event listener to the window which clears and resets a timer upon movement.
function MouseMoveTimeout() {
// Whatever you want the timeout to do
}
var TimerID;
function InstallMouseMoveTimeout(Install) {
var Timeout = 60000;
var MouseMoveDetector = function(e) {
clearTimeout(TimerID);
TimerID = setTimeout(MouseMoveTimeout, Timeout);
}
if(Install && TimerID == undefined) {
TimerID = setTimeout(MouseMoveTimeout, Timeout);
window.addEventListener('mousemove', MouseMoveDetector, true);
} else {
clearTimeout(TimerID);
window.removeEventListener('mousemove', MouseMoveDetector, true);
TimerID = undefined;
}
}
To use this in your code you would:
if (event.srcElement.value>=1) {
InstallMouseMoveTimeout(true); // Install mouse move timeout
...
} else {
InstallMouseMoveTimeout(false); // Cancel mouse move timeout
...
}
var idleTimer = null; // do this in the global scope
// do the following at the location where you want to reset the timer:
if(idleTimer) window.clearTimeout(idleTimer);
idleTimer = window.setTimeout(function() {
location.href = 'other-site';
}, 60000);
So whenever the second block of code is called the old timer is reset and a new one is started. However, since mousemove events trigger very often, this might screw up performance. In this case create an interval (setInterval()) which triggers e.g. every 10 seconds and only set the current date in your mousemove handler. Then you can simply check in your timer callback if enough time since the last mousemove has exceeded and in this case execute an action.
Sounds like a crazy UI idea! But if you want to do that, you need to declare this somewhere:
var timer;
When you want to start the timer running, do this:
timer = setTimeout(function() { timer = -1; doStuff(); }, seconds * 1000);
That will call doStuff after seconds has elapsed.
If you want to cancel the timer:
if (timer != -1) {
clearTimeout(timer);
timer = -1;
}
By combining these appropriately, you can solve your problem.

Categories