clearInterval/run function only once not working - javascript

The function and console.log("a") keep firing when I repeatedly move out of trw and moving back in, it just doesn't stop. How do I make the function stop after I've called onblur once?
var Hello = false;
var looper = setInterval(function() {
if (!Hello) {
trw.onblur = function() {
console.log("a");
clearInterval(looper);
Hello = true;
}
}
}, 1);

Don't use listener inside the interval better use outside
var Hello = false;
var looper = setInterval(function() {
if (!Hello) {
console.log("a");
}
}, 1);
document.getElementById('trw').onblur = function() {
console.log("stopped");
clearInterval(looper);
Hello = true;
}
<input type="text" id="trw">

Related

how to make an infinate loop in javascript

I am just starting in javascript, I would like to have a toggle button that runs a function until it's pressed again. I have some code for the toggle:
const backgroundButton = document.getElementById("backgroundButton"); //getting button from HTML
let clickToggle = 0; //defining a veriable used to store the state of the button
backgroundButton.addEventListener("click", function(){
if (clickToggle == 0) {
console.log('button was off');
//start loop
clickToggle = 1;
}
else {
console.log('button was on');
//stop loop
clickToggle = 0;
}
});
but, I don't know how to do an infinite loop, any help is greatly appreciated!
(PS: I know infinite loops crash, that's why I'm here)
You could use setInterval and clearInterval. A truly infinite loop would look like this:
while (true) doSomething();
But that is not what anyone wants, as it will block the user interface. Using setTimeout or setInterval you allow the event loop to continue to do its work.
I'll assume you want to repeat calling the function doSomething in this demo:
const backgroundButton = document.getElementById("backgroundButton");
let timer = 0;
const output = document.getElementById("output");
backgroundButton.addEventListener("click", function(){
if (timer == 0) {
console.log('button was off');
//start loop
timer = setInterval(doSomething, 50);
}
else {
console.log('button was on');
//stop loop
clearInterval(timer);
timer = 0;
}
});
function doSomething() {
output.textContent = +output.textContent + 1;
}
<button id="backgroundButton">Start/Stop</button>
<div id="output"></div>
You can do something like this. Hopefully following with resolve you're required scenario.
let isEnabled = false;
let interval;
function clickFunction() {
isEnabled = !isEnabled; // toggle enable flag
if (isEnabled) {
console.log('Set Interval', isEnabled)
interval = setInterval(function () {
console.log('Do some work.');
}, 1000);
} else {
console.log('Clear Interval', isEnabled)
clearInterval(interval);
}
}
<button onclick="clickFunction()">Click me</button>
You can also use Window.requestAnimationFrame() for the infinite loop.
const toggleButton = document.querySelector('#toggle');
let hasBegun = false;
let anim;
const tick = () => {
if (hasBegun) {
document.querySelector('#output').textContent += '+';
};
requestAnimationFrame(tick)
};
toggleButton.addEventListener("click", function() {
if (!hasBegun) {
console.log('Starting');
hasBegun = true;
anim = requestAnimationFrame(tick);
} else {
console.log('Stopping');
hasBegun = false;
cancelAnimationFrame(anim);
anim = null;
}
});
<button id="toggle">Start/Stop</button>
<pre id="output"></pre>

Cardio app: clear timer for interval located in function scope

Here is Cardio app on CodePen.
http://codepen.io/Mahmoud-Zakaria/pen/vxWzxW?editors=1010
When I want to stop the cardio by stop btn and clear its interval which its refernce in function scope, It doesn't stop/clear.
(function() {
//States
let i = 5;
let play = true;
//DOM
let cardioSec = document.getElementById('cardio-sec');
let cardioStart = document.getElementById('cardio-start');
let cardioStop = document.getElementById('cardio-stop');
//Render
function render(el) {
el.innerHTML = i
};
//Audio
let audio = new Audio("https://raw.githubusercontent.com/mahmoudZakaria90/myCodePenStuff/master/audio/Bepp-beep.mp3");
//Setup
function setInterVals(times, callback) {
i = times;
let timer = setInterval(function() {
console.log(i) //RENDER
render(cardioSec)
i--;
if (i < 1) {
clearInterval(timer);
audio.play();
callback();
}
}, 1000)
return timer;
}
function start() {
setInterVals(5, cardio);
}
function cardio() {
setInterVals(30, rest);
}
function rest() {
setInterVals(15, cardio);
}
function stopCardio() {
clearInterval(setInterVals())
}
cardioStart.onclick = start
cardioStop.onclick = stopCardio
})();
Done:
http://codepen.io/anon/pen/gmdLMr?editors=1010
The "timer" variable was out of the scope, by declaring it as global, you wont have problems ^^

How to incorporate delay on a function?

I'm trying to implement a delay on a function. Should I wrap the function inside a delay function? Or can I somehow add more code, so that the animation doesn't start before 5 sec after page load?
var typeThis = "blablablabla";
var displayText = "";
function type(fullString, typedSoFar) {
if (fullString.length != typedSoFar.length) {
typedSoFar = fullString.substring(0, typedSoFar.length + 1);
document.getElementById("logoType").innerText = typedSoFar;
setTimeout(function() {
type(fullString, typedSoFar)
}, 150);
}
}
document.getElementById("logoType").innerHtml = typeThis;
var element = document.createElement('h2');
element.innerHTML = typeThis;
typeThis = element.textContent;
type(typeThis, displayText);
<a class="navbar-brand" id="topper" href="#"><p id="logoType"></p></a>
I think what you are looking for is setTimeout.
window.setTimeout(function () {
type(typeThis, displayText);
}, 5000);
You can also add that to a listener to know when the window has finished loading:
window.addEventListener('load', function () {
window.setTimeout(function () {
type(typeThis, displayText);
}, 5000);
});
A full example:
var typeThis = "blablablabla";
var displayText = "";
function type(fullString, typedSoFar) {
if (fullString.length != typedSoFar.length) {
typedSoFar = fullString.substring(0, typedSoFar.length + 1);
document.getElementById("logoType").innerText = typedSoFar;
setTimeout(function() {
type(fullString, typedSoFar)
}, 150);
}
}
document.getElementById("logoType").innerHtml = typeThis;
var element = document.createElement('h2');
element.innerHTML = typeThis;
typeThis = element.textContent;
window.addEventListener('load', function() {
window.setTimeout(function() {
type(typeThis, displayText);
}, 5000);
});
Waiting 5 seconds...
<a class="navbar-brand" id="topper" href="#"><p id="logoType"></p></a>
Your best bet is not going to be adding more code to delay, but wrap this all in a Timeout: https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout
Use setTimeout() like so:
var timeoutID;
function delayedAlert() {
timeoutID = window.setTimeout(slowAlert, 2000);
}
function slowAlert() {
alert("That was really slow!");
}
function clearAlert() {
window.clearTimeout(timeoutID);
}
Source: https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout

How would I toggle the state of a setInterval function in jQuery?

I want to be able to click a an element with an id of pause to start a count of the elements in a time object and if I re click the pause it will stop it and reclick start it exactly like the toggle feature in JQuery but with a setInteval function how would I go about doing this?
$("#pause").click(function(ffe) {
if(on == true) {
on = false
alert("on");
}
else {
on = true;
alert("off");
}
if(on == false) {
setInterval(function() {
$("#timet ul").append("<li>" + $("#time ul")
.children('li').length +"</li>");
}, 100);
}
else {
alert("Error");
}
});
A classic technique is to use a single master setInterval loop and simply use if..else logic to determine what needs to run. This is how a lot of javascript games work:
var on = true;
// Our master scheduler:
setInterval(function() {
if (on) {
$("#timet ul").append("<li>" + $("#time ul")
.children('li').length +"</li>");
}
}, 100);
// Code to handle the pause button
$("#pause").click(function(ffe) {
on = !on;
}
You can use the setTimeout function, if you want to run the function once, setInterval runs continuously, try the following:
var on = false;
$("#pause").click(function(ffe) {
if (on) {
on = false;
setTimeout(function() {
$("#timet ul").append("<li>" + $("#time ul")
.children('li').length +"</li>");
}, 100);
} else {
on = true;
}
});
You need to use .clearInterval() to stop the execution.
Here is the code: (THE WORKING DEMO)
$("#pause").click((function () {
var interId = null;
var $ul = $("#timet ul");
return function (e) {
if (interId) {
$(this).text("start");
clearInterval(interId);
interId = null;
} else {
$(this).text("pause");
interId = setInterval(function () {
$ul.append($('<li>').text($('li', $ul).length));
}, 100);
}
};
}()));​

clearInterval(); then call interval again

I have a setInterval function
var auto_refresh = setInterval(function () {
if ($('#addNewJuicebox:visible')) {
clearInterval();
}
//rest of function
}, 8000); // refresh every 5000 milliseconds
I want to call the setInterval later again, what's the best way to do that?
Try breaking your code up into the storage of the interval and the setting.
var auto_refresh = "";
function startRefresh() {
if (auto_refresh != "") {
// already set
return;
}
auto_refresh = setInterval(function() {
if ($('#addNewJuicebox:visible')) {
clearInterval(auto_refresh);
auto_refresh = "";
}
}, 8000);
}
Added a jsfiddle example for demonstrating starting and stopping an interval
http://jsfiddle.net/Jf8PT/
This may be what you're looking for
Function TaskRunner(run, interval) {
this._taskId = null;
this._run = run;
this._interval = interval
}
TaskRunner.prototype.start = function(){
if (this._taskId) {
return; // Already running
}
this._taskId = setInterval(this._taskId, this._interval);
}
TaskRunner.prototype.stop = function(){
if (!this._taskId) {
return; // Not running
}
clearInterval(this._taskId);
this._taskId = null;
}
var task = new TaskRunner(
function(){
if ($('#addNewJuicebox:visible')) {
task.stop();
}
// Do the update
}, 5000);
Now you can call `task.start()` from anywhere in your code to restart it.
clearInterval takes in a reference to the timer that you want to clear, you need to pass that in to it:
var auto_refresh = null;
var refresh = function () {
if ($('#addNewJuicebox').is(':visible')) {
clearInterval(auto_refresh);
auto_refresh = null;
}
};
var start_refreshing = function() {
if(auto_refresh != null) return;
auto_refresh = setInterval(refresh, 8000);
};
start_refreshing();
Maybe you just want to use setTimeout() instead, so that you have the control you're looking for?

Categories

Resources