how to stop function in 5 seconds? Vue.js - javascript

this is my code
setInterval(this.randomImage, 250);
setInterval(this.randomPosition, 250);
setInterval(this.addImage, 250);
i want to stop addImage function in 5 seconds because images are adding infinitely!
i tried to do it by this way
let timesRun = 0;
const intervalAddImage = setInterval(function () {
timesRun += 1;
if (timesRun === 60) {
clearInterval(intervalAddImage)
}
this.addImage();
}, 250);
intervalAddImage();
but it doesn't work...
i am using Vue.js!

The following code runs a task every 250ms and stops after 5sec. I hope this will give you some inspiration.
var intervalId = setInterval(() => console.log("running"), 250);
setTimeout(() => clearInterval(intervalId), 5000);

So it works)
let timesRun = 0; // just change to this
function addImage(timesRun) { console.log(timesRun)}
const intervalAddImage = setInterval(function () {
timesRun += 1; // just change to this
if (timesRun === 4) {
clearInterval(intervalAddImage)
return; // add this
}
addImage(timesRun);
}, 250);

Here is your mistake: do not use this without being careful: you should take time to understand how this works in JavaScript.
In your code, you increment this.timesRun, but you test on timesRun which is never incremented.
This sample will work as you expect:
let timesRun = 0;
//const addImage = this.addImage;
const intervalAddImage = setInterval(function () {
timesRun += 1;
if (timesRun === 60) {
clearInterval(intervalAddImage);
}
//addImage();
console.log("Hello", timesRun);
}, 250);

Related

clearing interval after counter reach 0 or reset

I'm trying to make simple game but I have problem to manage counter and to clear interval after counter reaches 0 or I click reset button. It works when It reaches 0, but when I try to implement it to reset button, counter is reseting but then goes with double speed.
let counter = 60;
let healthPoints = 3;
let points = 0;
document.querySelector('.reset').addEventListener('click', resetGame);
function countTime() {
const timer = document.querySelector('.timer');
const countTime = setInterval(function () {
counter--;
timer.innerHTML = + counter;
if (counter == 0) {
alert('Game over')
clearInterval(countTime);
}
}, 1000)
}
function resetGame() {
newBoard();
counter = 60;
healthPoints = 4;
points = 0;
clearInterval(countTime);
}
The countTime argument your are passing to the clearInterval function inside the resetGame function is a reference to the function called countTime. You need to rename the variable and declare it globally:
let counter = 60;
let healthPoints = 3;
let points = 0;
let t = null;
document.querySelector('.reset').addEventListener('click', resetGame);
function countTime() {
const timer = document.querySelector('.timer');
t = setInterval(function () {
counter--;
timer.innerHTML = + counter;
if (counter == 0) {
alert('Game over')
clearInterval(t);
}
}, 1000)
}
function resetGame() {
newBoard();
counter = 60;
healthPoints = 4;
points = 0;
clearInterval(t);
}
setInterval returns a value that you pass to clearInterval() when you want to stop the timer. You need to save this in a scope where resetGame() can see it. You are declaring inside countTime() which means it's only in scope there.
Here I've named it interval and defined it outside both functions so both functions have access to it:
let counter = 60;
let healthPoints = 3;
let points = 0;
let interval;
document.querySelector('.reset').addEventListener('click', resetGame);
function countTime() {
const timer = document.querySelector('.timer');
interval = setInterval(function () {
counter--;
timer.innerHTML = + counter;
if (counter == 0) {
alert('Game over')
clearInterval(interval);
}
}, 1000)
}
function resetGame() {
counter = 60;
healthPoints = 4;
points = 0;
clearInterval(interval);
countTime()
}
countTime()
<button class="reset">Reset</button>
<div class = "timer"></div>
It is because you didn't actually cleared the interval, you must provide to the clearInterval function which needs an interval id in order to know which interval to clear. See https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval
This id is actually returned when you call the setInterval function, so your countTime variable is your interval ID.
This is why when it reaches zero it works it is because you are properly clearing the interval by provided its id to the clearInterval function and on the contrary you are just providing the function reference to the clearInterval function in your resetGame function
So what you can do is actually returning your intervalId from your countTime and provided this to your resetGame function :
function countTime() {
...
const timer = document.querySelector('.timer');
// I renamed it just to be clear
const countTimeIntervalID = setInterval(function () {
counter--;
timer.innerHTML = + counter;
if (counter == 0) {
alert('Game over')
clearInterval(countTime);
}
}, 1000)
return countTimeIntervalID
}
let countTimeIntervalID = countTime();
function resetGame() {
...
clearInterval(countTimeIntervalID);
}
Also, note that the reason why when you clicked the reset button it doubled the counter time it is because since you didn't clear the first one, it was still running so there were actually to intervals running and updating the same .timer dom element

How to get clearInterval() to work in a loop in JavaScript

So I'm trying to get a function to run once every second, and then after four seconds I want it to stop using clearInterval()
function dotdotdot(){
var x = 0;
setInterval(function(){
if (x>=3){
torpWri = torpWri + ".";
document.getElementById("torpTxt").innerHTML = torpWri;
x++;
}
else{
x = 0;
clearInterval();
}
},1000);
}
This is my function and it should stop after four seconds and then reset x to 0 for when I call it again.
function loadButton(){
torpWri = "Torpedo Loading"
if(torpLoadAmount[arNum]<5){
torpLoadAmount[arNum]++;
torpAmount--;
document.getElementById("torpCnt").innerHTML = torpAmount;
document.getElementById("torpTxt").style.visibility = "visible";
document.getElementById("butunload").disabled=true;
document.getElementById("butfire").disabled=true;
document.getElementById("torpTxt").innerHTML = torpWri;
dotdotdot();
}
else{
document.getElementById("torpTxt").style.visibility = "visible";
document.getElementById("torpTxt").innerHTML = "Torpedo Bay Full";
}
timer3();
}
This is how I'm calling it.
I'm just needed to know why it isn't running the function dotdotdot(); every second and then stopping after four. Then when I call it again it should all just reset. But it's not running...
I've been searching for a while and haven't found anything, so I came here.
(Also, please don't comment on my other code, I know there are probably easier ways to do it, but this is what I'm working with right now.)
setInterval returns a timerID, which needs to be passed to clearInterval.
var ticks = 0;
var intervalID = setInterval(function() {
if (++ticks == 4) {
clearInterval(intervalID);
}
}, 1000);
You could also use setTimeout instead, and just not schedule a new tick when the condition is met.
setTimeout(function callback(ticks) {
if (ticks > limit) {
return;
}
setTimeout(callback, 0, ++ticks);
}, 1000, 0)
You need to store the handle / intervalId for the interval when it is set and then use it when you want to clear the interval:
function dotdotdot(){
var x = 0;
var intervalId = -1;
intervalId = setInterval(function(){
if (x>=3){
torpWri = torpWri + ".";
document.getElementById("torpTxt").innerHTML = torpWri;
x++;
} else {
x = 0;
clearInterval(intervalId);
}
},1000);
}
More info: https://developer.mozilla.org/en-US/Add-ons/Code_snippets/Timers
setInterval will return a timerid. So do like
var timer = setInterval(fun......)
Then
clearInterval(timer)

Confused about SetInterval and closures

How can we repeatedly update the contents of a div using setInterval
I am using the question from this link as a reference How to repeatedly update the contents of a <div> by only using JavaScript?
but i have got few questions here
Can we do it without anonymous functions,using closures. I have tried but could not end up with any workable solution.
How can we make it run infinitely, with the following code it gets stopped once i reaches 10.
window.onload = function() {
var timing = document.getElementById("timer");
var i = 0;
var interval = setInterval(function() {
timing.innerHTML = i++;
if (i > 10) {
clearInterval(interval);
i = 0;
return;
}
}, 1000);
}
<div id="timer"></div>
I am confused about setIntervals and closures
can some one help me here
Thanks
You could do something like this with a closure. Just reset your i value so, you will always be within your given range.
window.onload = function() {
var updateContent = (function(idx) {
return function() {
if (idx === 10) {
idx = 0;
}
var timing = document.getElementById("timer");
timing.innerHTML = idx++;
}
})(0);
var interval = setInterval(updateContent, 1000);
}
<div id="timer"></div>
This one should be clearer.
function updateTimer() {
var timer = document.getElementById("timer");
var timerValue = parseInt(timer.getAttribute("data-timer-value")) + 1;
if (timerValue == 10) {
timerValue = 0;
}
timer.setAttribute("data-timer-value", timerValue);
timer.innerHTML = "the time is " + timerValue;
}
window.onload = function() {
setInterval(updateTimer, 1000);
}
<div id="timer" data-timer-value="0"></div>

How to use setTimeout with a "do while" loop in Javascript?

I'm trying to make a 30 second countdown on a span element (#thirty) that will be started on click of another element (#start). It doesn't seem to work. I would appreciate your help.
var countdown = function() {
setTimeout(function() {
var i = 30;
do {
$("#thirty").text(i);
i--;
} while (i > 0);
}, 1000);
}
$("#start-timer").click(countdown());
use this :
var i = 30;
var countdown = function() {
var timeout_ = setInterval(function() {
$("#thirty").text(i);
i--;
if(i==0){
i = 30;
clearInterval(timeout_);
}
}, 1000);
}
$("#start-timer").click(countdown);

.ScrollLeft in Firefox issue

I have this script:
<script>
Array.prototype.forEach.call(document.querySelectorAll(".thumbs div"), function ($div) {
$div.style.width = document.querySelectorAll(" img").length * 100 / 4 + "px";
});
document.querySelector("#next").onclick = function () {
var i = 100;
var intervalId = setInterval(function () {
document.querySelector(".thumbs").scrollLeft += 1;
if (i == 0) {
clearInterval(intervalId);
}
i--;
});
};
document.querySelector("#prev").onclick = function () {
var i = 100;
var intervalId = setInterval(function () {
document.querySelector(".thumbs").scrollLeft -= 1;
if (i == 0) {
clearInterval(intervalId);
}
i--;
});
};
</script>
That scrolls the slider thumbs when clicking the next or prev buttons. In Opera and Chrome, it works fine - with one click to the button, .thumbs scrolls 100px. But in Firefox, with one click, it scrolls 1px.
What can I do to fix that?
That's because you aren't passing an interval delay to setInterval, and so Firefox only runs it once. Other browsers seem to take it as if you were passing it 0 (the minimum delay).
Just pass 0 or any value you like, to both of your intervals.
http://jsfiddle.net/ar8au1o6/1/
var intervalId = setInterval(function () {
document.querySelector(".thumbs").scrollLeft += 1;
if (i == 0) {
clearInterval(intervalId);
}
i--;
}, 0); // <-- Set each interval in your code to 0,
// Or any other delay.
// If you set it to 0, the browser will pick the minimum delay.

Categories

Resources