Changer SetInterval Values After Interval - javascript

If I can try to make everyone understand what I am looking for, I am looking for the value of the interval to change to lets say "5000ms" after "1000ms" and then it would go on to the next value such as "2000ms" and repeat all over again! The current code I have is pretty much a stopwatch, It adds the number 1 to a paragraph every 1000ms. Any help is extremely appreciated!
<script>
function myFunction() {
clicks += 1;
}
setInterval(myFunction, 1000);
var clicks = 0;
function myFunction() {
clicks += 1;
document.getElementById("demo").innerHTML = clicks;
// connects to paragraph id
}
</script>
<p id="demo"></p>
<!--connects to getElementById-->

Don't use setInterval - this functions will perform the action in any given interval, which you set once.
Use setTimeout instead. Which performs the action only once after given interval, and then call it again and again with different interval values.

what about this
<script>
var clicks = 0;
myFunction(1000);
function myFunction( currentInterval ) {
clicks ++;
document.getElementById("demo").innerHTML = clicks;
if ( currentInterval == 1000 )
{
currentInterval = 5000;
}
else if ( currentInterval == 5000 )
{
currentInterval = 2000;
}
else
{
currentInterval = 1000;
}
setTimeout( function(){ myFunction( currentInterval ) }, currentInterval );
}
</script>
<p id="demo"></p>

you should try using recursive timeout instead of interval
var timeout = 1000;
var timer;
function startTimer() {
clearTimeout(timer);
timer = setTimeout(function() {
console.log('tick');
startTimer();
}, timeout);
}
startTimer();
// timeout = 2000
// timeout = 500
// clearTimeout(timer); to cancel
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>

This might look a little complicated but you can try something like this:
JSFiddle.
(function() {
var interval = null;
var limit = 5;
function initInterval(callback, index) {
var msToSec = 1000;
if (interval) {
clearInterval();
}
console.log("Delay: ", index)
interval = setInterval(callback, index * msToSec);
}
function clearInterval() {
window.clearInterval(interval);
interval = null;
}
function resetInterval(callback, count) {
clearInterval();
initInterval(callback, count);
}
function main() {
var count = 1;
var notify = function() {
console.log("Hello World: ", count);
var _nextCount = ((count++) % limit) + 1;
if (count < 10) {
resetInterval(notify, _nextCount);
} else {
console.log("Stoping loop...");
clearInterval();
}
}
initInterval(notify, count);
}
main()
})()

Related

How to stop and reset my countdown timer?

I'm trying to make my countdown timer do the following 4 things
When 'start' is clicked, change button to 'stop'
When 'stop' is clicked, stop the timer
When timer is stopped, show 'start' button
When 'reset' is clicked, reset the timer
$(document).ready(function() {
var counter = 0;
var timeleft = 5;
function nf(num) {
var s = '0' + num;
return s.slice(-2);
}
function convertSeconds(s) {
var min = Math.floor(s / 60);
var sec = s % 60;
return nf(min, 2) + ' ' + nf(sec, 2);
}
function setup() {
var timer = document.getElementById("timer");
timer.innerHTML = (convertSeconds(timeleft - counter));
var interval = setInterval(timeIt, 1000);
function timeIt() {
counter++;
timer.innerHTML = (convertSeconds(timeleft - counter));
if (counter == timeleft) {
clearInterval(interval);
}
}
}
$("#timer-button").click(function() {
setup();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I recently needed something like this too. I ended up writing an ES6 class for that.
In my solution, I used Events to notify other components about the timer. Here is a fiddle in which I met your needs, but I left my EventManager() calls to show what I actually did.
The used EventManager is this one. The timer counts in 100ms steps by default, but you can adjust this by calling startTimer() with the interval of choice.
class Timer {
constructor(maxTime, startValue = 0) {
// Actual timer value 1/10s (100ms)
this.value = startValue;
// Maximum time of the timer in s
this.maxTime = maxTime * 10;
this.timerRunning = false;
}
/**
* Starts the timer. Increments the timer value every 100ms.
* #param {number} interval in ms
*/
startTimer(interval = 100) {
if (!this.timerRunning) {
let parent = this;
this.timerPointer = setInterval(function() {
if (parent.value < parent.maxTime) {
parent.value++;
//EventManager.fire('timerUpdated');
$("span").text(parent.value / 10 + "/" + parent.maxTime / 10);
} else {
parent.stopTimer();
//EventManager.fire('timeExceeded');
$("button").text("Start");
this.resetTimer();
$("span").text("Countdown over");
}
}, interval);
this.timerRunning = true;
}
}
// Stops the Timer.
stopTimer() {
clearInterval(this.timerPointer);
this.timerRunning = false;
}
// Resets the timer and stops it.
resetTimer() {
this.stopTimer();
this.value = 0;
$("span").text("0/" + this.maxTime/10);
//EventManager.fire('timerUpdated');
}
// Resets the timer and starts from the beginning.
restartTimer() {
this.resetTimer();
this.startTimer();
}
}
let timer = new Timer(6);
$("#start-stop").click(function() {
if (timer.timerRunning) {
timer.stopTimer();
$("#start-stop").text("Start");
} else {
timer.startTimer();
$("#start-stop").text("Stop");
}
});
$("#reset").click(function() {
timer.resetTimer();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="start-stop">
Start
</button>
<button id="reset">
Reset
</button>
<span>Timer: </span>
const div = document.querySelector('div');
const btn = document.querySelector('#timerBtn');
const resetbtn = document.querySelector('#reset');
let startFlag = 0;
let count = 0;
let intervalId;
const ms = 1000;
div.textContent = count;
btn.addEventListener('click', function() {
startFlag = startFlag + 1;
if(startFlag%2 !== 0) { // Start button clicked;
btn.textContent = 'Stop';
startTimer();
} else {
btn.textContent = 'Start';
stopTimer();
}
});
resetbtn.addEventListener('click', function() {
count = 0;
div.textContent = count;
});
function startTimer() {
intervalId = setInterval(() => {
count = count + 1;
div.textContent = count;
}, 1000);
}
function stopTimer() {
clearInterval(intervalId);
}
<div></div>
<button id="timerBtn">Start</button>
<button id="reset">Reset</button>

clearInterval and set it again after x seconds

I want to do simple interval with with if, It is checking a variable's value and doing a function again().
again function contains clearInterval, i++ and setTimeout to call interval again after x seconds
var speed = 1000;
var wait = 0;
var i = 0;
function init() {
setInterval(function() {
if (i >= 6) i = 0;
if (i == 4) {
wait = 5000;
again(wait);
} else {
document.body.innerHTML = i;
i++;
}
}, speed);
}
function again(time) {
clearInterval(init());
i++;
setTimeout(function() {
setInterval(init(), speed);
}, time);
}
init();
I expect output like this:
1, 2, 3, Waiting x sec's , 5, 1, 2, ...
but code is doing some thing crazy, Its going faster and faster. I don't know why.
Here's a codepen with example (can crash your browser!)
Can you fix it and explain? Thanks
You are not clearing interval but use function inside clearInterval method. Method init which is used has no return statement so clearInterval gets undefined in attribute, so it is not clearing nothing.
Fixed code:
var speed = 1000;
var wait = 0;
var i = 0;
var interval=null;
function init() {
interval = setInterval(function() {
if (i >= 6) i = 0;
if (i == 4) {
wait = 5000;
again(wait);
} else {
document.body.innerHTML = i;
i++;
}
}, speed);
}
function again(time) {
clearInterval(interval);
i++;
setTimeout(function() {
init()
}, time);
}
init();
Function setInterval returns interval id and function clearInterval in attribute should get id of interval which we want to stop, so I created interval variable to save id. I am using this variable in clearInterval.
This is a small example how changing the delay of a setInterval call.
(function iife() {
var timer = null,
counter = 0;
function task() {
counter += 1;
console.log(counter);
// condition: every four reps
if (counter % 4 === 0) {
console.log("changed speed to 4 seconds");
return start(4000);
}
// condition: every seven reps
if (counter % 7 === 0) {
console.log("changed speed to 2 seconds");
return start(2000);
}
}
function start(delay) {
clearInterval(timer);
console.log("runs every " + delay + " miliseconds");
timer = setInterval(task, delay);
}
start(1000);
}());

Break while loop with timer?

I was wondering is it possible to break a while loop with a timer?
looked on the internet but could not find a solution for it.
while (true) {
alert('hi');
} if (timer < 0) {
timer?
document.write('Time is up!');
break;
}
Thank you.
You should use setTimeout for this.
var timer = 3;
setTimeout(excuteMethod, 1000);
function excuteMethod() {
alert(timer + ' call');
timer--;
if (timer >= 0) setTimeout(excuteMethod, 1000);
}
Demo : http://jsfiddle.net/kishoresahas/9s9z7adt/
I'm not sure if this is the correct approach, but it works,
(function() {
var delay = 30;
var date = new Date();
var timer = date.setTime(date.getTime() + delay);
var count = 0;
function validate() {
var now = new Date();
if (+now > timer)
return false;
else
return true;
}
while (true) {
count++;
console.log(count);
if (!validate()) {
console.log("Time expired");
break;
}
// Fail safe.
if (count > 50000) {
console.log("Count breached")
break;
}
}
})()
You can change control value in timer function and break the loop.
var control = true;
while(control)
{
...
}
setTimeout(function(){
control = false;
}, delay); //delay is miliseconds
Or based on counter
var control = true,
counter = 10;
while(control){
...
}
// you can handle as count down
// count down counter every 1000 miliseconds
// after 10(counter start value) seconds
// change control value to false to break while loop
// and clear interval
var counterInterval = setInterval(function(){
counter--;
if(counter == 0)
{
control = false;
clearInterval(counterInterval);
}
},1000);

setInterval countDown update time

I have this countDown, each time I press the buttons I want to add 5 more seconds.
When the time is updated the function count down the new value but the old value as well.
Can someone explain me why?
http://jsfiddle.net/xqdj3uz8/1/
$('button').on('click', function() {
var newtime = parseInt(seconds + 5);
timer(newtime);
});
You could try by using a global variable to track the amount of seconds left. Clicking on the button will increment this variable.
var timeLeft = 10;
function timer() {
var i = setInterval(function () {
$('span').text(timeLeft);
timeLeft--
if (timeLeft === 0) clearInterval(i)
}, 1000)
}
function addSeconds(n) {
timeLeft += n
}
timer()
$('button').on('click', function () {
addSeconds(5)
});
Demo (1): http://jsfiddle.net/xqdj3uz8/21/
please use it
function timer(time) {
var interval = setInterval(countDown, 1000);
function countDown() {
time--;
$('span').text(time);
if(time === 0) {
clearInterval(interval);
}
}
$('button').on('click', function() {
time=parseInt(time + 5);
$('span').text(time);
});
}
var seconds = 5;
timer(seconds);
Try This
Working JSFIDDLE
var gblTime=0;
function timer(time) {
var interval = setInterval(countDown, 1000);
gblTime = time;
function countDown() {
gblTime--;
$('span').text(gblTime);
if(gblTime <= 0) {
clearInterval(interval);
}
}
}
var seconds = 5;
timer(seconds);
$('button').on('click', function() {
gblTime = parseInt(gblTime +1+ 5);
//timer(newtime);
});
You are adding new intervals that are independent form each other, try:
var time = 5;
var seconds = 5;
function timer() {
var interval = setInterval(countDown, 1000);
function countDown() {
$('span').text(time);
if(time === 0) {
clearInterval(interval);
}
time--;
}
}
timer();
$('button').on('click', function() {
if(time==0){
timer();
}
time += seconds;
});

javascript autoreload in infinite loop with time left till next reload

i need a JavaScript, that relaods a page every 30 seconds, and will show how much time there is until next reload at the ID time-to-update, Example:
<p>Refreshing in <span id="time-to-update" class="light-blue"></span> seconds.</p>
i also need it to repeat itself infinitely.
thank you for reading, i hope it helps not me but everyone else, and a real big thank you if you could make this script.
(function() {
var el = document.getElementById('time-to-update');
var count = 30;
setInterval(function() {
count -= 1;
el.innerHTML = count;
if (count == 0) {
location.reload();
}
}, 1000);
})();
A variation that uses setTimeout rather than setInterval, and uses the more cross-browser secure document.location.reload(true);.
var timer = 30;
var el = document.getElementById('time-to-update');
(function loop(el) {
if (timer > 0) {
el.innerHTML = timer;
timer -= 1;
setTimeout(function () { loop(el); }, 1000);
} else {
document.location.reload(true);
}
}(el));
http://jsfiddle.net/zGGEH/1/
var timer = {
interval: null,
seconds: 30,
start: function () {
var self = this,
el = document.getElementById('time-to-update');
el.innerText = this.seconds; // Output initial value
this.interval = setInterval(function () {
self.seconds--;
if (self.seconds == 0)
window.location.reload();
el.innerText = self.seconds;
}, 1000);
},
stop: function () {
window.clearInterval(this.interval)
}
}
timer.start();

Categories

Resources