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

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

Related

Timer should starts and ends for each element in forloop in jquery

I am making a game. There are 6 players in the game. I want to start timer for each players turn.
$("#startgame").click(function() {
$(".player").each(function() {
$(".progressTimer").progressTimer({
timeLimit: 20,
warningThreshold: 10,
baseStyle: 'progress-bar-warning',
warningStyle: 'progress-bar-danger'
});
});
});
The problem is that a timer starts only one time and the loop executes without previous element animation stops.
And if one player play his turn in between his time interval. how could i stop his timer or clear his time interval and start the timer for next player
Question I: "How to execute the animation six times with single progress bar?"
You are right on for loop is synchronous and animation is asynchronous.
In the case that you only have one timer, not until the previous animation finishes, the next animation starts.
To fix this, you need to define a global varibale var i=0;, and add one more parameter in progressTimer, such as progressTimer({...},i). At the end of function progressTimer, increment i++, if(i<6), call itself again. So that you can make sure next animation executes by the time the previous animation finishes.
Code Example:
I found the source code link here progressTimer. Now I'm gonna demostrate my idea by modifying the code under jquery-progressTimer/demo/index.html.
This is the code sample by original author:
<div class="container">
<div class="loading-progress"></div>
</div>
<script src="js/static.min.js"></script>
<script src="../dist/js/jquery.progresstimer.js"></script>
<script>
var progress = $(".loading-progress").progressTimer({
timeLimit: 10,
onFinish: function () {
alert('completed!');
}
});
$.ajax({
url:"http://localhost/"
}).error(function(){
progress.progressTimer('error', {
errorText:'ERROR!',
onFinish:function(){
alert('There was an error processing your information!');
}
});
}).done(function(){
progress.progressTimer('complete');
});
</script>
Don't worry about the ajax code, because it's just showing when you can't get such a url, progress bar will finish the animation and alert an error. Hence, I comment out the ajax code because it has nothing to do with our case.
This is the code after I modified to make the progress bar process 6 times:
var i=0;
function fn() {
var progress = $(".loading-progress").progressTimer({
timeLimit: 5,
/* onFinish() gurantees when the animation finishes */
onFinish: function () {
i++;
alert('completed!');
if(i<6){
fn();
}
}
});
}
fn();
Now we are done!
Question II:
"if one player play his turn in between his time interval.. how could i stop his timer or clear his time interval and start the timer for next player."
Here is the second version based on sample code:
var i=0;
var myVar;
function fn() {
/*Player Initial state in this turn*/
var PlayerEndHisTurn=false;
/*Init seconds that past*/
var secondsPast=0;
/*Init progress animation*/
var progress = $(".loading-progress").progressTimer({
timeLimit: 5,
warningThreshold: 5,
onFinish: function () {
i++;
alert('completed!');
if(i<6){
fn();
}
}
});
/*We keep track of time every second*/
myVar=setInterval(function(){
secondsPast++;
//console.log(secondsPast);
/*Assume every player end his turn on the third second*/
if(secondsPast==3){
PlayerEndHisTurn=true;
}
/*If the player ends his turn*/
if(PlayerEndHisTurn){
/*Progress bar skips this player's turn, call complete*/
/*No need to call i++ because we called this in onFinish()*/
//i++;
progress.progressTimer('complete');
/*Stop timing for this player*/
clearInterval(myVar);
/*Prevent multiple interval function running*/
return myVar;
/*Start the next player's turn*/
fn();
}
/*if the player runs out his time*/
if(secondsPast==5){
clearInterval(myVar);
return myVar;
}
},1000);
}
fn();

Reset variable in Javascript on execute?

I am using this function to auto-click a button after 15 seconds. The problem is the user doesn't leave the page after the option is run and it may be re-run again on the same page but the timer continues. In fact, the timer continues even if I do the action myself.
<script type="text/javascript">
time = 15;
interval = setInterval(function() {
time--;
document.getElementById('Label1').innerHTML = "You must choose in " + time + " seconds"
if (time == 0) {
// stop timer
clearInterval(interval);
// click
document.getElementById('thebutton').click();
}
}, 1000)
</script>
So this script should run the timer and "press" the "thebutton" in fifteen seconds and then the timer should stop counting and reset until run again. If the button is pressed manually before 15 seconds it should still reset.
<input type='submit' id='thebutton' value='Done'></input>
Hopefully this is clear. I am still new and learning.
Set a base time and then reset it to that.
<script type="text/javascript">
time = 15;
baseTime = 15;
interval = setInterval(function() {
time--;
document.getElementById('Label1').innerHTML = "You must choose in " + time + " seconds"
if (time == 0) {
// stop timer
clearInterval(interval);
// click
document.getElementById('thebutton').click();
time = baseTime;
return false;
}
}, 1000)
</script>
I had a look at the code and the most critical thing that I think you should look at is that the button has no "onclick" function.
This means that clicking the button does nothing because you have not put a function there that does something when you click it.
I wrote some code that I hope helps:
let time = 15;
const label = document.getElementById("Label1");
const button = document.getElementById("thebutton");
const getText = () => `You must choose in ${time} seconds`;
const interval = setInterval(() => {
time--;
label.innerHTML = getText();
if (time === 0) {
// stop timer
clearInterval(interval);
// click
button.click();
}
}, 1000);
const stopTime = () => {
clearInterval(interval);
time = 15;
label.innerHTML = getText();
};
And in your html something like this:
<input type='submit' id='thebutton' value='Done' onclick="stopTime()" />
Finally I made a small video where I walk through the code, it could be useful as well: https://youtu.be/ZYS9AcxO3d4
Have a great day!
If you only want the button to be clicked once after 15 seconds then you should use the setTimeout() function instead of setInterval().
Then if you do not want the auto-click to happen if the user clicks the button then you would need to add an onClick handler to your button that calls clearTimeout().
I assume you want the label updated as the seconds count down? And it's unclear how the timer is started. Check the below code and see if it does what you expect.
var time, interval;
function stopTimer() {
if (interval) {
clearInterval(interval);
interval = null;
}
time = 15;
}
function timerAction() {
$('#lblStatus').text("You must choose in " + time + " seconds");
if (time-- <= 0) {
stopTimer();
console.log("done!");
$("#btnStop").click();
}
}
function startTimer() {
stopTimer();
timerAction();
interval = setInterval(timerAction, 1000);
}
$("#btnStart").click(function() {
startTimer();
});
$("#btnStop").click(function() {
stopTimer();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id=lblStatus></span>
<button id='btnStart'>Reset / Start</button>
<button id='btnStop'>Stop</button>
If you want to run only once, you can use setTimeout function
setTimeout(your code, 15000);

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>

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.

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.

Categories