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>
Related
I have an audio event that in the buffering is not loading quickly, i want to change some events.
so in audio, if the event 'waiting' is triggered do nothing unless it takes more than 5 seconds. Then run function X.
Here is a sample code:
$(audio).on("waiting", function () {
// RUN AFTER 5 SECONDS
console.log("This is taking way too long! Lets panic..");
$play.append('<div class="icon-loading"></div>');
});
$(audio).on("playing", function () {
// This is the function that runs after wait is over
console.log("Wait is over, it is loaded!");
$play.append('<span class="icon-play-button"></span>');
});
Thanks in advance.
Use setTimeout and clearTimeout as follows
let waitingTimeout;
$(audio).on("waiting", function() {
// RUN AFTER 5 SECONDS
waitingTimeout = setTimeout(() => {
console.log("This is taking way too long! Lets panic..");
$play.append('<div class="icon-loading"></div>');
}, 5000);
});
$(audio).on("playing", function() {
if (waitingTimeout) {
clearTimeout(waitingTimeout);
waitingTimeout = null;
}
// This is the function that runs after wait is over
console.log("Wait is over, it is loaded!");
$play.append('<span class="icon-play-button"></span>');
});
I'm trying to make a chrome extension and in my content script which runs only on www.youtube.com it's supposed to check, document.getElementById("movie_player"), if a particular div element has loaded or not. If not setInterval and wait a second. If it has loaded then run alert("Hello") and clearInterval which will end the script.
However, it's not working. Even after I find the element, and it says "Hello" it continues to say hello which means setInterval is still calling my function after 1000 milliseconds even though it should have been cleared.
Here's my content.js file:
var timeOut;
function CheckDOMChange()
{
moviePlayer = document.getElementById("movie_player");
if(moviePlayer !== null)
{
WhenVideoLoads();
}
timeOut = setInterval("CheckDOMChange();", 1000);
}
function WhenVideoLoads()
{
alert("Hello");
clearInterval(timeOut);
}
CheckDOMChange();
As you can see, I made timeOut a global variable so it shouldn't be a scope problem. So I really don't know what the problem is because the condition is being met and clearInterval is being called.
Any help would be much appreciated.
The issue is that you have setInterval inside the function. Basically, for every call you are setting interval which creates multiple setIntervals. Remove the setInterval from within the function
var timeOut;
function CheckDOMChange() {
moviePlayer = document.getElementById("movie_player");
if (moviePlayer !== null) {
WhenVideoLoads();
}
}
function WhenVideoLoads() {
alert("Hello");
clearInterval(timeOut);
}
timeOut = setInterval("CheckDOMChange();", 1000);
By calling CheckDOMChange recursively, you are actually exponentially creating timers, and you are only clearing the last timer when calling WhenVideoLoads.
You may try to run this snippet and inspect the console to see what is happening, and see that clicking the button will clear the last timer but not all those that have been created before.
var timeOut;
var counter = 0;
function CheckDOMChange()
{
console.log("counter :", counter);
if (counter > 16) {
console.log("Stop creating new timers!");
return;
}
timeOut = setInterval("CheckDOMChange();", 5000);
console.log("timeOut :", timeOut);
counter ++;
}
function WhenVideoLoads()
{
console.log("Clearing ", timeOut);
clearInterval(timeOut);
}
CheckDOMChange();
<button onclick="WhenVideoLoads()" id="clear">Clear timer</button>
You should avoid calling CheckDOMChange recursively, and proceed as #cdoshi suggested.
Hope this helps!
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 ..
I have a function that contain setTimeout() Method.
I have a button that calls that function, so you could hit this button multiple times and call this function as many times as you want.
Is there a way to actually execute this function, only if there is no other instance of this function that has an active timer?
You would have to keep track of whether you had previously set this timer or not and whether it was still active by using some sort of variable that had a scope that persisted across multiple button presses.
There is no built-in function that will tell you whether the timer you started with this button is still running. You have to create your own. It could work something like this:
var buttonTimer;
function myButtonClick() {
if (!buttonTimer) {
buttonTimer = setTimeout(function() {
buttonTimer = null;
// put your timer code here
}, 2000);
}
}
This will ignore the button click as long as there is a currently active timer. When there is no timer running, it will set a new timer.
Because you're keeping track of the actual timer ID, you have the freedom to implement other behaviors too such as cancelling the previous timer (such as a stop button) or reset the timer to a new time interval by cancelling the previous timer and then setting a new one.
Try this:
var Timer = function() {
var self = this;
this.running = false;
this.run = function() {
if(!self.running) {
self.running = true;
console.log('starting run');
setTimeout(function() {
self.running = false;
console.log('done running!');
}, 5000);
} else {
console.log('i was running already!');
}
}
return this;
}
var aTimer = new Timer();
And add a button for testing purposes:
<button onclick="aTimer.run()">Run!</button>
Fiddle: http://jsfiddle.net/kukiwon/FCuNh/
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();
}
}