How to change the interval dynamically when using setInterval - javascript

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>

Related

How do i make a function repeat in javascript with ajustable timings

i want to make this code work:
let wait = 1;
function speedup(){
wait = 0.5
}
// I want it so that if the speed-up button is pressed the code repeats but faster
<html>
<body>
<a onclick="speedup()">speed up</a>
<p id="p">0</p>
</body>
</html>
Can anyone help? I need to use it for a game where the user can press a button to speed up a lengthy process for igc.
You can do something like:
let delay = 1000; // time in millisecond
let intervalId;
function speedUp() {
delay = Math.max(0, delay - 100); // don't get negative time
interval();
}
function interval() {
// Clear existing interval
if (intervalId) {
clearInterval(intervalId);
}
intervalId = setInterval(() => {
// run some code
}, delay);
}
// Setup the first interval
interval();
// Call speedUp will cancel the previous setInterval, and start another one, 100msec faster

Exit popup + setInterval

I'm trying to create something like Exit Popup but limited to users residing on my page less than 10 seconds. I thought to use setInterval:
var counter = 0;
var myInterval = setInterval(function () {
// count
console.log(counter);
// Clear if more than 10 seconds
if ( 10 < counter ) {
console.log('Stop setInterval');
clearInterval(myInterval);
}
++counter;
}, 1000);
if ( 10 > counter ) {
// Simplified exit popup function
$(window).mouseleave(function() {
console.log('Popup');
clearInterval(myInterval);
});
}
First part of code works, but the second part executes even if counter is greater than 10. Why this is not working as it should?
No need for a counter. Just bind the event at page load, and unbind it after X seconds using a setTimeout:
$(window).bind('mouseleave', exitPopup);
setTimeout(function(){
$(window).unbind('mouseleave', exitPopup);
},10000);
function exitPopup(){
alert('Exit popup');
}
JS Fiddle Demo (3 seconds)
For this demo, make sure to put your cursor in the lower right window right at the beginning, and wait 3 seconds. It should not appear after that. If you don't wait, it'll show the popup.

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/

Delaying a timed interval function?

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.

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