Confused about SetInterval and closures - javascript

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>

Related

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)

java script Foreach loop

Javascript
function myFunction() {
for (i = 0; i < 5000;) {
setTimeout(function() {
document.getElementById("demo").innerHTML = i;
}, i);
i += 500;
}
}
HTML
<body onload="myFunction()">
<div id="demo"></div>
How to increase " i " every 5ms and print it in #demo every time it changes
I am trying to make a look that increases the value of ( i ) once every 5ms, and prints it out in # demo.
Right now, the value 5000 immediately prints out as soon as I run the script for some reason, as opposed to increasing by 500 every time.
Thanks in advance.
You can change myFunction to:
var i = 0;
function myFunction() {
var timerId = setInterval(function(){
if(i >= 5000)
{
clearInterval(timerId);
}
document.getElementById("demo").innerHTML = i;
i +=500;
}, 5);
}
this should work.
var i=0;
function looper(){
setTimeout(function(){
console.log(i+" data");
i=i+500;
if(i<5000)
looper();
}, i);
}
looper();
function myFunction() {
var i = 0;
var max = 5000;
var step = 500;
var intervalMs = 5;
var interval = setInterval(function() {
// clear interval if one step before max value
if (i >= max-step) {
clearInterval(interval);
}
// increment i by step
i+=step;
// set inner html of div
document.getElementById("demo").innerHTML = i;
}, intervalMs)
}
Plunkr: https://plnkr.co/edit/IfkGOpjUnf4sKpN4iCZ4?p=preview
If you want your code to look similar to what you have, you can use an IIFE:
function myFunction() {
for (i = 0; i <= 5000;i += 500) {
(function(index) {
setTimeout(function() {
document.getElementById("demo").innerHTML = index;
}, index);
})(i);
}
}
<body onload="myFunction()">
<div id="demo"></div>
</body>
You are having an issue with the closure not saving a reference to your timeout. Subsequent arguments after the second are passed into the callback function as arguments.
Here we are passing i as the third argument
setTimeout(fn, delay, i)
Then in the callaback we have access to the i, we are reassigning it to x within the scope of the callback.
function myFunction() {
for (i = 0; i <= 5000; i = i + 500) {
setTimeout(function(x) {
document.getElementById("demo").innerHTML = x;
}, i, i);
}
}
myFunction()
<div id="demo"></div>
function myFunction(max, ii = 0) {
document.getElementById('demo').innerHTML = ii
if (ii < max) {
setTimeout(myFunction, 500, max, ii + 500)
}
}
myFunction(5000)
<div id="demo"></div>
**
<div id="demo"></div>
<script>
function myFunction() {
var i = 0;
var setClock = function() {
if (i < 5000) {
local = i;
i += 500;
setTimeout(function() {document.getElementById("demo").innerHTML = local; setTimeout(setClock, 500);},
500);
}
}
setClock();
}
**
you should wrap scripts in tags
the javascript Closures. You should know that because of the Closures, second parameters for all setTimeout() are 5000, which is the i's final value. You can avoid the Closure by the codes I showed or erase the impact of Closure by below codes:
<div id="demo"></div>
<script>
function myFunction() {
var local;
for (i = 0; i < 5000; i+= 500) {
local = i;
setTimeout((function(interval){
return function() {document.getElementById("demo").innerHTML = interval;} ;
})(local), (function(interval){return interval})(local));
}
}

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);

Where do I place my "document.getElementById("").innerHTML = "";" Within my Javascript?

At the moment I am creating an on screen timer in javascript. This is the code for my timer:
var i = 30;
function startTimer() {
var countdownTimer = setInterval(function() {
console.log(i);
i = i - 1;
if (i < 0) {
clearInterval(countdownTimer);
}
}, 1000);
}
I am just wondering where I should place my document.getElementById("time-remaining").innerHTML = "Time Remaining:" + i;
I am also wondering if the above document.getElementById is correct (will it be displayed as a onscreen timer or will it fail or something)?
Thanks in advanced.
Try this:
var i = 30;
function startTimer() {
var countdownTimer = setInterval(function () {
console.log(i);
i = i - 1;
if (i < 0) {
clearInterval(countdownTimer);
return; //This will prevent -1 to be written to html
}
document.getElementById("time-remaining").innerHTML = "Time Remaining:" + i;
}, 1000);
}
startTimer();
Dont forget to call the function.
Demo: http://jsfiddle.net/GCu2D/842/
You can put the
document.getElementById("time-remaining").innerHTML = "Time Remaining:" + i;
After the startTimer function or really anywhere.
And yes thedocument.getElementById is correct, if your html id is the same one as in javascript.

JQuery Auto Click

I have a problem, I have 3 button lets say it's called #pos1, #pos2 and #pos3.
I want to makes it automatically click #pos1 button in 2 seconds, after that click the #pos2 after another 2 seconds, and #pos3 after another 2 seconds,
after that back to the #pos1 in another 2 seconds and so on via jQuery.
HTML
<button id="pos1">Pos1</button>
<button id="pos2">Pos2</button>
<button id="pos3">Pos3</button>
Anyone can help me please?
Try
$(function() {
var timeout;
var count = $('button[id^=pos]').length;
$('button[id^=pos]').click(function() {
var $this = $(this);
var id = $this.attr('id');
var next = parseInt(id.substring(4), 10) + 1;
if( next >= count ){
next = 1
}
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(function() {
$('#pos' + next).trigger('click');
}, 2000);
})
timeout = setTimeout(function() {
$('#pos1').trigger('click');
}, 2000);
})
var posArray = ["#pos1", "#pos2", "#pos3"];
var counter = 0;
setInterval(function() {
$(posArray[counter]).triggerHandler('click');
counter = ((counter<2) ? counter+1 : 0);
}, 2000);
That should do the trick, though you did not mention when you want it to stop running.
Well I don't know what you already have but technically it could be done via triggerHandler()
var currentPos = 1,
posCount = 3;
autoclick = function() {
$('#pos'+currentPos).triggerHandler('click');
currentPos++;
if(currentPos > posCount) { currentPos = 1; }
};
window.setInterval(autoclick,2000);
If I have understood you question right, you need to perform click in a continuous loop in the order pos1>pos2>pos3>pos1>pos2 and so on. If this is what you want, you can use jQuery window.setTimeout for this. Code will be something like this:
window.setTimeout(performClick, 2000);
var nextClick = 1;
function performClick() {
if(nextClick == 1)
{
$("#pos1").trigger("click");
nextClick = 2;
}
else if(nextClick==2)
{
$("#pos2").trigger("click");
nextClick = 3;
}
else if(nextClick == 3)
{
$("#pos3").trigger("click");
nextClick = 1;
}
window.setTimeout(performClick, 2000);
}
This is quite buggy but will solve your problem.
using setInterval()
Calls a function or executes a code snippet repeatedly, with a fixed time delay between each call to that function.
var tempArray = ["pos1", "pos2", "pos3"]; //create an array to loop through
var arrayCounter = 0;
setInterval(function() {
$('#' + tempArray[arrayCounter ]).trigger('click');
arrayCounter = arrayCounter <2 ? arrayCounter +1 : 0;
}, 2000);
fiddle here
check your console for fiddle example

Categories

Resources