Why reseting setInterval it continues to call multiple function instance not one? - javascript

I have problem to pause and play setInterval, whenever I clearInterval and var = setInterval(func,time), it multiplies the instances on interval, and it starts to call 2 func per tick and so on.
Here is jsfiddle with non-working example http://jsfiddle.net/wZWWT/
Here is the code:
function test() {
$(".container").append("<div>Inserted text</div>");
}
var timer = setInterval(test,2000);
$(".container").on("mouseenter mouseover",function(){
clearInterval(timer);
}).on("mouseleave mouseout",function(){
timer = setInterval(test,2000);
})

Makes sense. Mouseleave and mouseout are two different events. So you've got two intervals created.
When you create a new interval the old one isn't destroyed. It continues working even if you don't store the reference to it
before setting a new interval try to check if you've another interval running:
$(".container").on("mouseenter mouseover",function(){
clearInterval(timer);
}).on("mouseleave",function(){
if ( !timer ) timer = setInterval(test,2000);
}).on("mouseout",function(){
if ( !timer ) timer = setInterval(test,2000);
})

The timer is actually just an integer that represents the setInterval(). If you assign a new setInterval() to it, then timer will have the ID of the new setInterval() but the old one is not cancelled, and you don't know the ID for it to do so with the ID overwritten.
In your code the on() is calling both mouseenter and mouseover - both are firing but only the ID of the last one to execute is set to the timer variable, so when it is called (twice, but it doesn't really do any harm) in your mouseleave/mouseout it can only cancel one of them.

Related

I need help creating a loop in dev console in firefox

I am trying to use the dev console to give mario a mushroom every 5 seconds (in the browser game super mario html5)
I can give mario mushrooms manually by typing marioShroons(mario) but I would like to have it on loop so I don't have to pause the game every time I want a mushroom. I have tried a while loop and set timeout but I can't figure it out. The only coding languages I familiar with are c++ and html.
**
while(data.time.amount > 0) {
killOtherCharacters()
}
setTimeout(function() {
killOtherCharacters()
}, 1000);
I expected these lines of code to not give me a mushroom, but to automatically kill enemies. But on the first try (the while loop) it froze the tab and I had to reload the page.
With the set timeout, it didn't make any obvious results, it killed all near characters once and then stopped.
You tried using setTimeout, and it only worked once. This is to be expected, because:
Window.setTimeout() sets a timer which executes a function or specified piece of code once the timer expires
From MDN
What you need to do is use setInterval:
The setInterval() method...repeatedly calls a function or executes a code snippet, with a fixed time delay between each call.
From MDN
So in your console, you should write this:
setInterval(killOtherCharacters, 1000);
(I removed the anonymous function because it wasn't needed - you only need an anonymous function if you're passing parameters or doing multiple things. You do need to remove the () for this though).
And if you want to stop the function from executing, assign a variable to the interval:
var killCharacters = setInterval(killOtherCharacters, 1000);
Then call clearInterval upon this variable to clear the interval (stop the loop):
clearInterval(killCharacters);
The reason your while loop froze the page is because Javascript can only do one thing at a time and you told it to always run your while function, blocking all other Javascript from running on your site.
setTimeout is only run once after a set time (see documentation), if you want to run something every x miliseconds it's better to use setInterval instead.
var intervalID = window.setInterval(killOtherCharacters(), 500); //run this every 500 ms
Use setInterval if you want killOtherCharacters() to be called repeatedly.
const interval = setInterval(function() {killOtherCharacters() },1000);
Then when you want the function to stop being called:
clearInterval(interval);

jwplayer onTime() calling setInterval() several times per second

My main goal is at 7:45 in the video to display a countdown timer from 20:00.
Here is my event called by the jwplayer I'm using:
onTime: function(event){showTimer(event.position);}
Here is my funciton showTimer:
function showTimer(video_position){
// Schedule the update to happen once every second
if(Math.round(video_position) == 465){
setInterval(updateTimer, 1000);
}
};
The Problem:
Because it onTime() isn't guaranteed to hit right at 465.0 I have to d a Math.round on the video position. If I do this, 4-10 onTime event handlers knock off within 465.0 - 466.0 so my setInterval() gets called several times and the timer counts down insanely fast.
Is there a way to make it hit the setInterval() once or maybe a global variable I can set the first time to let setInterval() know its already been knocked off?
I'd just use a boolean flag to check whether the event has fired yet.
var fired = false;
if(Math.round(video_position) == 465 && !fired){
fired = true;
setInterval(updateTimer, 1000);
}
That way it can only fire the event once.

prevent javascript setInterval function stacking up

I have a function that runs on a click event that uses javascript's setIterval for some of my animations (i'm doing a game) so the problem is that if a user clicks while the animation is still displaying (setInterval is still executing) the setInterval is stacking up in the event stack or that is what I found out thus either crushing my game or running twice as fast (the animation). My question is is there any way to prevent event stacking? I do not want the setInterval to stack up on the previous setInterval and so on. I know that I could use clearInterval function like so:
var timerInterval = setInterval(drawPlayerRunning, 50);
clearInterval(timerInterval);
but it does not really work as I want it to, because what if user clicks many times while the function is still is executing, the clearInterval will only get rid of last event of the event stack leaving all the previous ones still in the "game". Any idea how to prevent this event stack up, or at least removing them efficiently?
You can create a flag that monitors the interval state:
1)
var isIntervalInProgress = false;
setInterval(function()
{
if ( isIntervalInProgress )
return false;
isIntervalInProgress = true;
drawPlayerRunning();
isIntervalInProgress = false;
}, 50);
or just a timeout that will run itself once it's finished:
2)
var func = function()
{
setTimeout(function()
{
drawPlayerRunning();
func();
}, 50)
}
whichever you like
You want to use requestAnimationFrame. It is designed with games in mind, and if your code happens to be too slow, it will reduce your frame rate accordingly (from 60 fps to 30 fps for instance). But it won't stack-up events.
Edit: Sorry, I think I misunderstood your question. Let me try again.
You should have only one draw function which is called every few milliseconds (set the interval up with requestAnimationFrame(draw)).
A click should not add a new interval, but rather create a floatingAnimation object and add it to the list of objects to render. All animation objects will be rendered by the draw function everytime the browser calls draw. In the arguments passed to draw, there will be a timestamp. Use this timestamp minus the creation date of floatingAnimation to determine how to draw the floating thing above the character.

javascript reset an interval

I need to be able to call this function to reset the interval.
I know this has been asked before. But the answer given at
Javascript - Reset setInterval back to 0
is not working for me.
Here is the code that I tried:
function startTimer(){
clearInterval(interval);
var interval = setInterval(function(){
advanceSlide();
}, 5000);
};
I call that at the beginning of my page to start a slideshow that changes every 5 seconds. and I use this code to call it again, witch I expected would reset that 5 seconds.
onclick=startTimer();>
The onclick does one other thing too, but this is what is not working. The other action takes place but the interval does not change, its still going based off the same portion of 5 seconds that was left before I clicked.
You need to declare the variable outside the function...
var interval;
function startTimer() {
clearInterval(interval);
interval = setInterval(advanceSlide, 5000);
}
Otherwise it is lost when the function exits.

jQuery - When not keyPress(), keyUp() for 2 secs do function()

How can you set the opposite of keyPress, keyup, keydown etc. Something like if the user starts to type something and then stop, after 2 seconds do function(){}
I tried onKeyPress with delay but it doesn't seem to work.
Thanks
You can use keyPress and a global timer. Just reset the timer every time the user press a key.
I guess the code is something like:
var myTimer = undefined;
var delayTime = 2000; // should be in miliseconds.
function myfunction() {
// do your stuff here
}
function onKeyPress(e) {
if (myTimer) {
clearTimeout(myTimer);
}
myTimer = setTimeout('myfunction();', delayTime);
}
PS: I have not tested this code.
On a key event, you set a 2 second timer. If another key event comes in before the timer goes off, you stop the timer and set a new one. If the timer fires, then there's been 2 seconds of no typing.
Well, one oldschool way to do it is to use setTimeout and clearTimeout. Basically, every time a keypress happens, you cancel the previous timeout, and then set up a new one with a 2 second delay. The function call will only actually go through once someone stops pressing keys for 2 seconds, which I think is what you've asked for
I don't know whether any native way of doing this. But i have used this plugin to perform this.

Categories