setTimeOut is not waiting for proper delay time - javascript

I have two buttons play and stop. When I click play I want the images to run like a slideshow.
I am using setTimeout() and having it wait 5 seconds before running.
When play is clicked, the code runs fine , waiting for 5 seconds and then displaying the next image, but when I click stop , and then click play again, it stops waiting the correct interval.Instead of waiting for 5 seconds before running, it waits for one second for the first two images and then 5 seconds for the next, again for one second for the next two and so on..
Why is it running correctly the first time and then breaking on retry?
Code:
var stop = false;
playClickfunction() {
showImages();
}
showImages() {
//code to display image for all no of images
//and user can stop on any no of image..
if(!stop)
setTimeout(showImages, 5000);
}
stopClickfunction() {
stop = true;
}

you need to clear the Timeout on stop.
maybe try something like that:
var timer = false;
playClickfunction()
{
showImages();
}
showImages()
{
//code to display image for all no of images
//and user can stop on any no of image..
if(!stop)
timer = setTimeout(showImages, 5000);
}
stopClickfunction()
{
clearTimeout( timer )
}

Try using the proper way than with a flag variable
var timer = setTimeout(showImages, 5000);
clearTimeout(timer);

you should use the method clearTimeOut() for that

If you click stop, then click start again before the 5 seconds has elapsed, the first timeout will keep running. What you need to do is clear the timeout, not just to stop the images, but every time start is clicked, e.g.:
var timeout;
function start() {
stop();
showImages();
}
}
function stop() {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
}
function showImages() {
// do stuff, then
timeout = setTimeout(showImages, 5000);
}
Alternatively, if start is clicked and the timeout is set, just ignore the click since the timer is already running. In that case you'd do:
function start() {
if (!timeout) {
showImages();
}
}

Related

Boolean statement not evaluating in javascript

I'm writing a script, and there are two boolean statements that are very similar but giving different results, and I don't see why they conflict with one another.
My function looks like this:
SCRIPT:
(function() {
window.onload = function() {
let stopped = true;
let button = document.getElementById("start-stop");
if (stopped) {
setInterval(function() {
console.log("The timer is working.");
}, 1000);
}
button.addEventListener('click', function(){
if (stopped) {
stopped = false;
console.log(stopped);
} else {
stopped = true;
console.log(stopped);
}
});
}
}
}).call(this);
The basic idea is that when I push the button the setInterval function stops, however it keeps on going even when the if/else function switches stopped to false.
For example, my console.log looks like this:
I.e. stopped = false, but setInterval doesn't terminate.
Why is this not evaluating correctly?
The problem with your code is that you are trying to work on a piece of code that has already started to operate. In simpler words, the setInterval method will be called every 1000ms, no matter what the value of stopped variable is. If you wish to really stop the log, you can do any of these:
clearInterval()
to completely remove the interval or
setInterval(function() {
if (stopped) {
console.log("The timer is working.");
}
}, 1000);
to check if the value of stopped variable has changed or not (after the click) and act accordingly. Choose either of these for your purpose..
you are calling setinterval even before button is clicked .As the event is already triggered you cannot stop just by setting the variable to false ,you need to clear the interval using clearinterval
check the following snippet
var intervalId;
window.onload = function() {
let stopped = true;
let button = document.getElementById("start-stop");
var Interval_id;
button.addEventListener('click', function() {
if (stopped) {
Interval_id = callTimeout();
stopped = false;
} else {
clearInterval(Interval_id);
stopped = true;
}
});
}
function callTimeout() {
intervalId = setInterval(function() {
console.log("The timer is working.");
}, 1000);
return intervalId;
}
<input type="button" id="start-stop" value="click it">
Hope it helps
Put the if(stopped) statement inside the setInterval function because if you used this function once it will keep going..
Another way to stop setInterval function is by using clearInterval, like this
var intervalId = setInterval(function() { /* code here */}, 1000)
// And whenever you want to stop it
clearInterval(intervalId);
When you click the button stopped variable becomes false but the setInterval will not stop because the setInterval code is already executed.. it will not execute again on button click. And if you reload the page what will happen is that stopped variable will be again set to true as you have written at first line and setInterval will execute again ..
Now What you can do is store setInterval in a variable like this
var timer = setInterval(function,1000);
and then when you click the button use this method to clear interval
clearInterval(timer);
this should do the trick .. Hope it helps ..

ClearInterval function doesn't work in my case

function active_timer(){
var time = 5000;
interval = setInterval(function(){
console.log('interval');
},time);
}
active_timer();
socket.on('timer', function (data) {
console.log('here') // it triggered
clearInterval(interval); // don't work
active_timer() //resume
});
I tried this and it won't work because the console.log still triggered every 5 sec. Any clue why?
Your code is technically running correctly but your console logs are misleading.
You've started an interval which triggers every 5 seconds. Each time your socket even fires, you clear the interval but then immediately start a new one. This gives the illusion that there's no gap in the intervals, but there is.
You can test this by changing your console.log('interval') to console.log(interval). So instead of just printing "interval", it will print out the value of the variable referencing the interval object. This is represented by a number which will change each time the interval is stopped and restarted.
Just to be clear, an interval cannot be resumed, only new ones started and existing ones stopped.
var interval = null;
function startTimer() {
// store the reference to our interval
interval = setInterval(function() {
console.log('triggered interval', interval);
}, 2000);
console.log('new interval started', interval);
}
startTimer();
// button click to simulate your socket event
$('#simulate').on('click', function() {
console.log('received simulated event');
clearInterval(interval);
startTimer();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="simulate">Simulate Socket Event</button>

How to make a warning to user when 10 secs. to refresh setInterval?

I am using setInterval to refresh a content of graph in page. How to make a show an alert to user when setinterval is about to refresh that 'the content will be refreshed'.
For example my interval is using 300 secs and I want to show an alert after 290 seconds have passed that 'The content will be refreshed after 10 secs. Do you want to refresh the graph' for each interval. How to do this? Any suggestions?
You should set you interval to 290000ms, and then it will show an alert, and then you use setTimeout to update your page after 10 seconds, like so:
setInterval(function() {
alert("10 seconds to update")
setTimeout(function() {
//REFRESH PAGE
},5000);
}, 10000);
On your page loading you can put your 290 secs refresh
setInterval(function(){
showDialogBox("do you want to refresh");
}, 290000);
and then add a action on the confirm button that will be delayed the last 10sec
confirmButtonOnClick(){
setInterval(function(){
refresh();
}, 10000);
}
In cases like this, I prefer to use setTimeout over setInterval as it gives better control.
So I set two timers -- one for the warning and then another for the timeout itself, then I restart the two timers.
const timeoutWarning = 1800;
const timeoutDone = 2000;
function showWarning() {
console.log('About to time out...');
}
function doTimeout() {
console.log('Timeout reached');
setWarnings();
}
function setWarnings() {
setTimeout(showWarning, timeoutWarning);
setTimeout(doTimeout, timeoutDone);
}
setWarnings();
Something like that:
var interval;
var secondsPassed = 0;
function refreshWithMessage() {
interval = setInterval(function(){
if(secondsPassed == 290) {
//showMessage with options
}
if(secondsPassed == 300) {
clearInterval(interval);
//do what you need here (refresh page?)
}
secondsPassed++;
}, 1000)
}
If you need to let user cancel the interval - you should just clear interval and then reset seconds variable to 0.

how can I rearrange this code so my setInterval stops looping infinitely?

I'm trying to make a simple flip-card/memory match (like from super mario brothers 3) game in HTML/Javascript and am having a slight issue with the setInterval command.
Here is a link to the full code: http://jsfiddle.net/msfZj/
Here is the main issue/main logic of it:
if(click == 2) //denotes two cards being clicked
{
if(flippedArray[1].src === flippedArray[0].src) // if click 1 == click 2 then refer to function 'delayMatch' which sets click 1 and 2 cards to not be displayed
{
window.setInterval(function() { delayMatch() }, 500);
console.log("EQUAL");
}
else
{
window.setInterval(function() { delayNoMatch() }, 500); // if click 1 != click 2 then display card.png
console.log("NOT EQUAL");
}
function delayMatch() //function for matching pairs
{
flippedArray[0].style = "display:none;";
flippedArray[1].style = "display:none;";
}
function delayNoMatch() //function for non-matching pairs
{
flippedArray[0].src = "card.png";
flippedArray[1].src = "card.png";
}
click = 0; // when clicked two cards set click back to zero
}
The first two cards I click on always work: but from that point onward the setInterval keeps running the function over and over again in an endless loop every 500ms.
I'd be extremely appreciative if anybody can point my in the right direction on how I can do this properly.
Thank you very much for your time.
It looks like you need setTimeout, which only runs once?
window.setTimeout(function() { delayMatch() }, 500);
Otherwise, you need to clear the interval with clearInterval(i), but first set "i" using the return value of setInterval:
var i = window.setInterval(function() { delayMatch() }, 500);
Here's a demo (I JQuerified it a bit for JSFiddle).
You're going to want to go with setTimeout() instead of setInterval()
A handy function when you use setTimeout is clearTimeout. Say you want to set a timer, but maybe want a button to cancel
var timer = setTimeout(fn,1000);
//later maybe
clearTimeout(timer);

setInterval again in 5 seconds after clearInterval button

I'm doing a content slider that automatically cycles slides (by periodically calling the "next" function using setInterval)but stops when the user click on a prev/next buttons (by using clearInterval on the prev/next buttons). Is there a way to use setInterval again after a few seconds of clicking the button?
Code:
// start to automatically cycle slides
var cycleTimer = setInterval(function () {
$scroll.trigger('next');
}, 450);
// set next/previous buttons as clearInterval triggers
var $stopTriggers = $('img.right').add('img.left'); // left right
// function to stop auto-cycle
function stopCycle() {
clearInterval(cycleTimer);
}
Put your setInterval in a function and then call that function with setTimeout().
The difference between setInterval() and setTimeout() is that setInterval() calls your function repeatedly at each interval, while setTimeout() calls your function only once after the specified delay.
In the code below I've added a function startCycle(). Call that function to, well, start the cycle, both immediately so that it starts automatically and from a timeout set within your existing stopCycle() function.
var cycleTimer;
function startCycle() {
cycleTimer = setInterval(function () {
$scroll.trigger('next');
}, 450);
}
// start to automatically cycle slides
startCycle();
// set next/previous buttons as clearInterval triggers
var $stopTriggers = $('img.right').add('img.left'); // left right
// function to stop auto-cycle
function stopCycle() {
clearInterval(cycleTimer);
setTimeout(startCycle, 5000); // restart after 5 seconds
}

Categories