I the given code, I am using setInterval() and clearInterval() methods.
Here are two buttons for setInterval() and two for clearInterval(), if I click both setInterval() buttons, then the clearInterval() buttons doesn't work.
HTML:
<div id="a"></div>
<button id='bt1'>start</button>
<button id='bt2'>Stop</button>
<button id='bt3'>Start</button>
<button id='bt4'>Stop</button>
Javascript:
var Graph = {
graph: null,
start: function (i) {
this.graph = setInterval(function () {
$('#a').html(i++);
}, 1000);
},
stop: function () {
window.clearInterval(this.graph);
}
};
$('#bt1').click(function(){
Graph.start(1);
});
$('#bt2').click(function(){
Graph.stop();
});
$('#bt3').click(function(){
Graph.start(1);
});
$('#bt4').click(function(){
Graph.stop();
});
Fiddle: Fiddle
As the other answers, the first timer ID is overwritten. Try to store the IDs separately in an array or at least as separate variable names. Here is one adjustment using an array:
var Graph = {
graph: [0, 0], /// turn this into an array
start: function(id, i) { /// add a new parameter here
this.graph[id] = setInterval(function () {
$('#a').html(i++);
}, 1000);
},
stop: function (id) { /// add parameter here as well
window.clearInterval(this.graph[id]);
}
};
$('#bt1').click(function(){
Graph.start(0, 1); /// set index 0 with this timer id
});
$('#bt2').click(function(){
Graph.stop(0); /// stop using id at index 0
});
$('#bt3').click(function(){
Graph.start(1, 1); /// etc.
});
$('#bt4').click(function(){
Graph.stop(1);
});
Your i variable may be subject to the same thing depending on what you try; I haven't addressed that here.
Hope this helps.
You only have a single variable to store the result of both calls to setInterval, i.e. you are overwriting it on the second call so the first timer can't be cleared.
The clearInterval() method clears a timer set with the setInterval() method.
The ID value returned by setInterval() is used as the parameter for the clearInterval() method.
Note: To be able to use the clearInterval() method, you must use a global variable when creating the interval method:
myVar = setInterval("javascript function",milliseconds);
Then you will be able to stop the execution by calling the clearInterval() method.
You can also refer to this answer
If you click the #bt1 button and then the #bt3 button, the second start() function call will overwrite the graph variable in the Graph object. So the ID value returned by first setInterval() call is lost, you cannot clear the first timer.
Just put the following line of code before the setInterval() call in the start() method. This will stop the previous running timer:
if (this.graph) { this.stop(); }
Like this:
var Graph = {
graph: null,
start: function (i) {
if (this.graph) { this.stop(); }
this.graph = setInterval(function () {
$('#a').html(i++);
}, 1000);
},
stop: function () {
window.clearInterval(this.graph);
}
};
$('#bt1').click(function(){
Graph.start(1);
});
$('#bt2').click(function(){
Graph.stop();
});
$('#bt3').click(function(){
Graph.start(1);
});
$('#bt4').click(function(){
Graph.stop();
});
Related
I am trying to making live variable which updates every second which works but when I add count function there then there I can see 0 for 1 second and after that variable shows without animation. My goal is to make variable which at first load page counts from 0 to "var. value" for example 18 and if variable change for example to 20, then there will be count ani. from 18 to 20. I don't actually know how I can achieve it because I can't get previous variable because it's store in global_users.php
index.php
<script>
$(document).ready(function() {
$("#players").load("global_users.php")
setInterval(function () {
$("#players").load("global_users.php")
}, 1000);
});
</script>
<span class="Count" id="players"></span>
<script>
$('.Count').each(function () {
$(this).prop('Counter',0).animate({
Counter: $(this).text()
}, {
duration: 1000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
});
</script>
global_users.php
<?php
include("php/server.php");
echo $total_online = $serverInfo['Players'];
?>
The issue lies in the usage of .load() method, which can be useful, but not for this case. Under the hood of .load() is $.ajax() which allows you to make a request to the server with jQuery. Use it to get access to the player count value that the server returns with each request.
Split up the code in two functions, one for getting the player count and one for updating the player count with an animation. Whenever the first function has downloaded a new count and that count is different from the one that you already have, call the second function to update and animate.
<span class="count" id="players"></span>
$(document).ready(function() {
// Set starting count.
let count = 0;
const $players = $('#players');
/**
* Updates the player count with an animation and
* saves the new player count.
*/
function updatePlayerCount(newCount) {
$({
counter: count // Starting value, which is the last known count value.
}).animate({
counter: newCount // Value to animate to, which is the new count value.
}, {
duration: 1000,
easing: 'swing',
step: function() {
$players.text(Math.ceil(this.counter));
},
complete: function() {
count = newCount; // Update the count value after the animation to compare it later again.
}
});
}
/**
* Gets the count value from the server and
* passes it to the updatePlayerCount function
* if the count has been changed.
*/
function getPlayerCount() {
$.ajax({
url: 'global_users.php',
method: 'GET'
}).done(function(newCount) {
newCount = Number(newCount); // Makes sure that the value is a number.
if (count !== newCount) {
updatePlayerCount(newCount); // newCount is a different value than count, so updatePlayerCount is called.
}
});
}
// Execute getPlayerCount every 5 seconds.
setInterval(getPlayerCount, 5000);
});
I want to run the function continuously. But it only works first time properly. Is there any solution for working this function continuously?
$(document).ready(function() {
setInterval(() => {
$('#open-band').trigger('click');
setTimeout(() => {
$('#close-band').trigger('click');
}, 50000);
}, 15000);
});
If the code inside the setInterval takes longer than the time you have set it will create another process before the function finishes messing everything up. So choosing setTimeout is actually better.
To make a function loops in setTimeout use a following syntax:
function function1() {
// something here
}
function runner() {
function1();
setTimeout(function() {
runner();
}, time);
}
runner();
Given the comment under the question explaining your goal:
I want to trigger a button to show a div after 15 secs when the page is loaded, and 50 secs later another trigger for closing the div. & I want to run this continuously
I would suggest that you chain setTimeout() calls instead of using setInterval() which will cause the events to overlap and become a mess. I'd also suggest that you call show() and hide() directly on the required elements instead of faking click events in the DOM. Try this:
function openBand() {
$('#yourElement').show();
setTimeout(closeBand, 50000);
}
function closeBand() {
$('#yourElement').hide();
setTimeout(openBand, 15000);
}
$(document).ready(function() {
setTimeout(openBand, 15000);
// or just call closeBand() here directly, if the element starts as hidden
});
You should change your current function with this one
$(document).ready(function() {
setInterval(() => {
$('#open-band').trigger('click');
}, 15000);
setTimeout(() => {
$('#close-band').trigger('click');
}, 50000);
});
script
$(document).ready(function () {
var meter_id = $("#MeterReadingTypes li a.link_active").attr("id");
var range_id = $("#DateRangeTypes li a.link_active").attr("id");
window.setInterval(PostMainChartValues(meter_id, range_id), 5000);
...
});
function PostMainChartValues(meter_id, range_type_id) {
$.ajax({
...
});
}
window.setInterval is not trigerred. If I write an alert in setInterval it works. What is the reason of this? Why function is not triggering? I tracked it with chrome DevTools, and there is no move.
The first parameter to setInterval should be a function (or an evalable string). Right now, you are calling PostMainChartValues() and passing its return value to setInterval().
Change it to:
window.setInterval(function() {
PostMainChartValues(meter_id, range_id);
}, 5000);
This is not an ajax issue. You are using in wrong mode the setInterval parameter.
Create an anonymous function like bellow:
window.setInterval(function () { PostMainChartValues(meter_id, range_id); }, 5000);
I'm trying to make a wall post like Facebook. I need to refresh the content div after every ten seconds and the div shouldn't refresh while the user is typing a comment. The content is reloading but is not stopping. Actually, I want to stop it when i click id = 'comments_option'.
I tried this and called the function reload(uid) at $(document).ready
var intervalId = null;
function reload(uid) {
intervalId = setInterval(function () {
var ol = $('#home_list');
var start = ol.children().length;
$.post('ajax/reloadhome.php', {
uid: uid,
start: start
}, function (data) {
$('#buzzfetch ul').html(data);
});
}, 5000);
$('#comments_option').click(function () {
clearInterval(intervalId);
});
}
Use on as opposed to click:
$("#comments_option").on("click", function () {
clearInterval(intervalId)
});
Because #comments_option is inside of #buzzfetch ul, the click event will only be bound to the first instance of #comments_option when using click. It will not bind to any further instances.
See this answer for further explanation on the differences between bind and on
I am trying to use SetInterval and clearInterval in YUI
The code is written so it will create element every second and on mouse hover of div it should stop creating element.
http://jsbin.com/awadek/5
Please let me know what is wrong with my code?
You should pass an anonymous function as a handler to "mouseover". Otherwise, Javascript will attempt to evaluate and call the return from clearInterval (in this case, an integer!). The following code will work:
YUI().use("console", "console-filters", "substitute", "node-event-simulate",
function(Y) {
console.log("YUI is ready");
var doSomething = function(e) {
Y.one("#seconds").append("<p>I am number four</p>");
};
IntervalId = setInterval(doSomething, 1000);
//Notice the anonymous function below:
Y.one("#clearInt").on('mouseover', function() { clearInterval( IntervalId ) });
});
Here is your JSBin, ftfy. Enjoy!