setInterval not updating with variable - javascript

When I run the code it only intervals at the initial variable I created "2000". When i click on the button it doesn't change the interval to "50". Does anyone know why?
<html>
<body>
<h1 id="pressme"> Press me! </h1>
</body>
<script>
amount = 2000;
var i = 1;
document.getElementById("pressme").onclick = function() {
amount = 50;
}
function doSomething() {
i++;
console.log("I did something! " + i);
}
setInterval(doSomething, amount)
</script>
</html>
This isn't the OG code, more a simplified version of it.

You should use setInterval with clearInterval together.
<html>
<body>
<h1 id="pressme"> Press me! </h1>
</body>
<script>
amount = 2000;
var i = 1;
var handler
document.getElementById("pressme").onclick = function() {
amount = 50;
clearInterval(handler);
handler = setInterval(doSomething, amount);
}
function doSomething() {
i++;
console.log("I did something! " + i);
}
handler = setInterval(doSomething, amount);
</script>
So when click button, you should remove original setInterval handler and recreate it.

The interval was already set with the 2s, if you change the variable after that, it won't make any difference.
I recommend you do this:
let amount = 2000;
let interval = setInterval(doSomething, amount);
var i = 1;
document.getElementById("pressme").onclick = function () {
clearInterval(interval);
amount = 50;
setInterval(doSomething, amount);
}
function doSomething() {
i++;
console.log("I did something! " + i);
}

Related

how to make it have a wait until it executes a new code

So how do I make it wait 1000 milliseconds until it executes a different code(btw, What is the JavaScript version of sleep()? IS NOT helping me, so PLEASE don't close this question(and I'm not very good with JavaScript)).
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>Start</title>
</head>
<body>
<div id="changeText" style="font-family:verdana;"><br><br>
Press ENTER to continue</div>
<script>
document.addEventListener('keydown',function(e){
if(e.keyCode==13){
newPageTitle = 'Executing...';
document.title = newPageTitle;
//wait goes here
newPageTitle = 'Loading...';
document.title = newPageTitle;
//wait goes here
newPageTitle = 'Fetching Data...';
document.title = newPageTitle;
//wait goes here
newPageTitle = 'Done!';
document.title = newPageTitle;
//wait goes here
window.location.href=('https://example.com');
}
});
</script>
<script>
var text = ["<br><br>Press ENTER to continue_", "<br><br>Press ENTER to continue"];
var counter = 0;
var elem = document.getElementById("changeText");
var inst = setInterval(change, 700);
function change() {
elem.innerHTML = text[counter];
counter++;
if (counter >= text.length) {
counter = 0;
}
}
</script>
</body>
</html>
what I want it to do is whenever you press enter it changes the title, then it waits 1000 milliseconds to change the tile again, and then it waits 680 milliseconds to redirect you to another webpage (also for some reason when it's in the code snippet you have to click the snippet area and the you can press enter).
To do your animation on the document title, that would be a serie of nested setTimeout() function looking like this:
setTimeout(function () {
document.title = "Executing...";
setTimeout(function () {
document.title = "Loading...";
setTimeout(function () {
document.title = "Fetching Data...";
setTimeout(function () {
document.title = "Done!";
setTimeout(function () {
window.location.href = "https://example.com";
}, 1000);
}, 4000);
}, 3000);
}, 2000);
}, 1000);
I agree that is ugly. And you would have to calculate the added delays from outer to inner... So you could have a function to set the timeouts and make your code readable and maintainable.
Notice that nice looking script:
wait(1000, 'Executing...')
wait(2000, 'Loading...')
wait(3000, 'Fetching Data...')
wait(4000, 'Done!')
wait(1000)
Here is a demo where I console logged the title texts... Because we won't see the effect otherwize, since the snippet is an iframe.
document.addEventListener('keydown', function(e) {
if (e.keyCode == 13) {
wait(1000, 'Executing...')
wait(2000, 'Loading...')
wait(3000, 'Fetching Data...')
wait(4000, 'Done!')
wait(1000)
}
});
var text = ["<br><br>Press ENTER to continue_", "<br><br>Press ENTER to continue"];
var counter = 0;
var elem = document.getElementById("changeText");
var inst = setInterval(change, 700);
function change() {
elem.innerHTML = text[counter];
counter++;
if (counter >= text.length) {
counter = 0;
}
}
// A global variable to sum up the delays
let wait_time = 0;
function wait(delay, message) {
// Each "wait" call is adding its delay to the global wait_time
wait_time += delay
// This is the delay to use in this timeout
// "let" making it scoped to this function call
let timeoutDelay = wait_time;
console.log(timeoutDelay)
// Set a timeout
setTimeout(function() {
// If there is a message, use it on the title.
// else, redirect
if (message) {
console.log(message)
document.title = message;
} else {
window.location.href = ('https://example.com');
}
}, timeoutDelay)
}
<div id="changeText" style="font-family:verdana;"><br><br> Press ENTER to continue</div>

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

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>

increment value of a number with a specific timer-value

I've tried and looked around but I could not find anything similar.
<div> <span>23</span>/ 30 </div>
My thought process here is that I want 23 to increment in 1 value every 15th second.
And when it hits 30, it shall stop counting. I have no idea how to make it "stop" counting and how I should approach a problem like this.
Any help would be much appreciated!
Here is a possible solution, note that I do an iteration every second for the demo, but you can lower the rate by doing setTimeout(count,15000);.
var wrapper, value, timer;
window.addEventListener('load', startCounter, false);
function startCounter(){
document.querySelector('button').onclick = startCounter;
wrapper = document.querySelector('span');
value = 22;
count();
}
function count(){
clearTimeout(timer);
value++;
wrapper.innerHTML = value;
if(value < 30){ timer = setTimeout(count,1000); }
}
<div> <span>23</span>/ 30 </div>
<button>reset</button>
<div id="show"></div>
<script>
function timer(){
var i = 0;
setInterval(function(){
i++;
document.getElementById("show").innerHTML = i;
if(i > 30){
i = 0;
}
},1000);
}
timer();
</script>
//just super simple hope can be inspiration done thank
If a class is added to the span element like so:
<div> <span class="counter">23</span>/ 30 </div>
Then this javascript code would work:
var currentCount = parseInt($('.counter').text());
var increaseCount = function() {
if (currentCount < 30) {
currentCount = currentCount + 1;
$('.counter').text(currentCount);
setTimeout(increaseCount, 15000);
}
return;
};
setTimeout(increaseCount, 15000);
Here is an example with the timer set to a second:
https://jsfiddle.net/aqe43oLa/1/
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
var i = 24;
var timer=setInterval( increment, 15000);
function increment(){
if(i<=30)
{
console.log(i);
$('.increase').html('').append(i);
i++;
}
else
{
clearInterval(timer);
}
}
</script>
</head>
<body>
<div><span class="increase">23</span>/ 30 </div>
</body>
</html>

jQuery Timed Counter from a user supplied interval

My ultimate goal is to create a timer that produces a sound at an interval supplied by the user. For example, they input 10 into a field, and then a beep occurs every 10 seconds. Right now, I'm just having trouble with getting the setInterval to display the effect in a span. Any help getting me back on track is greatly appreciated. Thanks!
<div id="ping_div">
<p>
Enter the desired interval in milliseconds to sound ping noise. <br />
<input id="ping_val" type="text" /> <input id="set_ping" type="button" value="Submit" /><span id="ping_alert"></span>
</p>
<p>
<input id="go" type="button" value="Click to Start Pings" />
<span id="progress"></span>
</p>
</div>
____________________________
$(document).ready(function() {
$('#set_ping').click(function() {
interval = $('#ping_val').val();
$('#ping_alert').text('The ping will sound every ' + interval + ' milliseconds.');
});
$('#go').click(function() {
setInterval(timer, interval);
});
function timer() {
var base = base + interval;
$('#progress').text(base);
}
});
Your code works as-is, but it would be more obvious if you made a few changes:
http://jsfiddle.net/PxENF/3/
$(document).ready(function() {
var base = 0, interval = 1000; // <-----
$('#set_ping').click(function() {
interval = parseInt($('#ping_val').val(),10); // <-----
$('#ping_alert').text('The ping will sound every ' + interval + ' milliseconds.');
});
$('#go').click(function() {
setInterval(timer, interval);
});
function timer() {
base = base + interval; // <-----
$('#progress').text(base);
}
});
$('#go').click(function() {
interval = $('#ping_val').val();
$('#ping_alert').text('The ping will sound every ' + interval + ' milliseconds.');
setInterval(timer, interval);
});
You could make the interval self supporting, without declaring global variables:
$("#go").click(function() {
var interval = $("#ping_val").val();
setInterval(function(){
var progress = $("#progress");
var html = progress.html();
var offset = html.length > 0 ? parseInt(html) : 0;
progress.html(offset + interval);
}, interval);
});
Remember, each time you click "go" a new interval is started. These will interfere with eachother. This would be better:
var runningInterval = 0;
$("#go").click(function() {
clearInterval(runningInterval);
$("#progress").html("0");
var interval = $("#ping_val").val();
runningInterval = setInterval(function(){
var progress = $("#progress");
var html = progress.html();
var offset = html.length > 0 ? parseInt(html) : 0;
progress.html(offset + interval);
}, interval);
});

Categories

Resources