I want to reload data via javascript/jQuery into html div id elements every second. The initial load (ready-state) works perfectly, but in the refresh (via setInterval()) doesn't. I'm just a hobbyist programmer and would be very thankful for your help.
$(document).ready(function() {
$.getJSON('db/blackmagic/webscripts/jquery_gpio.php', function(json_php) {
document.getElementById("jq_zeitstempel").innerHTML = json_php.jq_zeitstempel;
document.getElementById("jq_bcm05").innerHTML = json_php.jq_bcm05;
document.getElementById("jq_bcm06").innerHTML = json_php.jq_bcm06;
setInterval(function() {
$.getJSON('db/blackmagic/webscripts/jquery_gpio.php', function(json_php_refresh) {
document.getElementById("jq_zeitstempel").innerHTML = json_php_refresh.jq_zeitstempel;
document.getElementById("jq_bcm05").innerHTML = json_php_refresh.jq_bcm05;
document.getElementById("jq_bcm06").innerHTML = json_php_refresh.jq_bcm06;
}
}, 1000);
});
});
I would create a single function instead and just call that in interval.
loadjSON = function() {
$.getJSON('db/blackmagic/webscripts/jquery_gpio.php', function(json_php) {
document.getElementById("jq_zeitstempel").innerHTML = json_php.jq_zeitstempel;
document.getElementById("jq_bcm05").innerHTML = json_php.jq_bcm05;
document.getElementById("jq_bcm06").innerHTML = json_php.jq_bcm06;
});
}
$(document).ready(function() {
setInterval(loadjSON, 1000);
});
Ex 1
In case, when you want to do the request no matter if previous was finished or not - you can wrap whole your logic in setInterval, like this:
$(document).ready(function () {
setInterval(function() {
$.getJSON("db/blackmagic/webscripts/jquery_gpio.php", function (json_php) {
document.getElementById("jq_zeitstempel").innerHTML = json_php.jq_zeitstempel;
document.getElementById("jq_bcm05").innerHTML = json_php.jq_bcm05;
document.getElementById("jq_bcm06").innerHTML = json_php.jq_bcm06;
});
}, 1000);
});
Ex 2
But if you need to wait a second after previous was finished, you can do kind of recursion here.
$(document).ready(function () {
function getJSON() {
$.getJSON("db/blackmagic/webscripts/jquery_gpio.php", function (json_php) {
document.getElementById("jq_zeitstempel").innerHTML = json_php.jq_zeitstempel;
document.getElementById("jq_bcm05").innerHTML = json_php.jq_bcm05;
document.getElementById("jq_bcm06").innerHTML = json_php.jq_bcm06;
setTimeout(getJSON, 1000);
});
}
getJSON();
});
How it works
In first example it simply calls your function every second.
In second, we wrap your function and call itself at the end of the request, after a second of waiting.
Related
I have a javascript code like this :
function loadlink() {
$('#load_here').load('1.php', function () {
$(this).unwrap().addClass('scale-in');
});
}
loadlink(); // This will run on page load
setInterval(function () {
loadlink() // this will run after every 5 seconds
}, 60000);
As you see this script will load 1.php in div#load_here every 1 minute.
My concern is currently I have more than 1 php files (lets called them 1.php, 2.php, 3.php, 4.php, 5.php, etc.) and I want them to load consecutively every 1 minute? I have no idea to do this
Thanks in advance
You can do something like
<script>
var index = 1;
function loadlink() {
$('#load_here').load(index + '.php', function () {
$(this).unwrap().addClass('scale-in');
});
}
loadlink(); // This will run on page load
var timer = setInterval(function () {
index++;
loadlink() // this will run after every 1 minute
if(index == 5) {
clearInterval(timer);
}
}, 60000);
</script>
<script>
var files=['1.php','2.php','3.php']//etc
function loadlink(file) {
$('#load_here').load(file, function () {
$(this).unwrap().addClass('scale-in');
});
}
loadlink(files[0]); // This will run on page load
setInterval(function () {
var nextFile=files.shift();
loadlink(nextFile) // this will run after every 5 seconds
files.push(nextFile);
}, 60000);
</script>
calling link after every5 sec and in last will call first php. also clear setInterval after call finished.
$(document).ready(function(){
var arr = ['php1','php2','php3','php4','php5'], i = 0;
function loadlink(link) {
console.log('calling link : ', link);
$('#load_here').load(link, function () {
$(this).unwrap().addClass('scale-in');
});
}
var intervalId = setInterval(callFileLink, 60000);
function callFileLink() {
var link = arr[i];
console.log("Message to alert every 5 seconds"+ link);
if(link) {
loadlink(link);
}else {
clearInterval(intervalId);
loadlink(arr[0]);
}
i++;
};
});
myfucntion = send request after 5 sec
document.ready(myfucntion)
$(window).focus(myfucntion)
$(window).blur(stop(myfucntion))
is this possible to stop a function on blur called previously in document.ready
Have a global timer:
var intervalId;
And it would be better to have two functions:
startfunction() {
intervalId = setTimeout(function () {
// send request after 5 seconds
}, 5000);
}
stopfunction() {
clearTimeout(intervalId);
}
And use them like this:
$(document).ready(startfunction);
$(document).ready(function () {
$(window).focus(startfunction);
$(window).blur(stopfunction);
});
Here is an example of how to make what you want work
var timer; // make it global so it can be accessed inside functions
var myFunction = function () {
timer = setTimeout(function() {
//do something after 5 seconds
}, 5000);
}
var stopMyFunction = function () {
clearTimeout(timer);
}
$(document).ready(myFunction)
$(window).focus(myFunction)
$(window).blur(stopMyFunction))
I can't figure out how to do it.
I have two separate scripts. The first one generates an interval (or a timeout) to run a specified function every x seconds, i.e. reload the page.
The other script contains actions for a button to control (pause/play) this interval.
The pitfall here is that both sides must be asyncronous (both run when the document is loaded).
How could I properly use the interval within the second script?
Here's the jsFiddle: http://jsfiddle.net/hm2d6d6L/4/
And here's the code for a quick view:
var interval;
// main script
(function($){
$(function(){
var reload = function() {
console.log('reloading...');
};
// Create interval here to run reload() every time
});
})(jQuery);
// Another script, available for specific users
(function($){
$(function(){
var $playerButton = $('body').find('button.player'),
$icon = $playerButton.children('i');
buttonAction = function(e){
e.preventDefault();
if ($(this).hasClass('playing')) {
// Pause/clear interval here
$(this).removeClass('playing').addClass('paused');
$icon.removeClass('glyphicon-pause').addClass('glyphicon-play');
}
else {
// Play/recreate interval here
$(this).removeClass('paused').addClass('playing');
$icon.removeClass('glyphicon-play').addClass('glyphicon-pause');
}
},
buttonInit = function() {
$playerButton.on('click', buttonAction);
};
buttonInit();
});
})(jQuery);
You could just create a simple event bus. This is pretty easy to create with jQuery, since you already have it in there:
// somewhere globally accessible (script 1 works fine)
var bus = $({});
// script 1
setInterval(function() {
reload();
bus.trigger('reload');
}, 1000);
// script 2
bus.on('reload', function() {
// there was a reload in script 1, yay!
});
I've found a solution. I'm sure it's not the best one, but it works.
As you pointed out, I eventually needed at least one global variable to act as a join between both scripts, and the use of a closure to overcome asyncronous issues. Note that I manipulate the button within reload, just to remark that sometimes it's not as easy as moving code outside in the global namespace:
Check it out here in jsFiddle: yay! this works!
And here's the code:
var intervalControl;
// main script
(function($){
$(function(){
var $playerButton = $('body').find('button.player'),
reload = function() {
console.log('reloading...');
$playerButton.css('top', parseInt($playerButton.css('top')) + 1);
};
var interval = function(callback) {
var timer,
playing = false;
this.play = function() {
if (! playing) {
timer = setInterval(callback, 2000);
playing = true;
}
};
this.pause = function() {
if (playing) {
clearInterval(timer);
playing = false;
}
};
this.play();
return this;
};
intervalControl = function() {
var timer = interval(reload);
return {
play: function() {
timer.play();
},
pause: function(){
timer.pause();
}
}
}
});
})(jQuery);
// Another script, available for specific users
(function($){
$(function(){
var $playerButton = $('body').find('button.player'),
$icon = $playerButton.children('i'),
interval;
buttonAction = function(e){
e.preventDefault();
if ($(this).hasClass('playing')) {
interval.pause();
$(this).removeClass('playing').addClass('paused');
$icon.removeClass('glyphicon-pause').addClass('glyphicon-play');
}
else {
interval.play();
$(this).removeClass('paused').addClass('playing');
$icon.removeClass('glyphicon-play').addClass('glyphicon-pause');
}
},
buttonInit = function() {
$playerButton.on('click', buttonAction);
interval = intervalControl();
};
buttonInit();
});
})(jQuery);
Any better suggestion is most welcome.
I have an ajax request that refreshes a page using setInterval every 5 seconds.
Within that ajax request I have another setInterval function to blink a every half second if a condition is true.
What happens is it seems to work fine after the initial ajax call. However, with every 5 second refresh ajax refresh, my blink function timer is halved, effectively doubling the speed.
Any help would be appreciated, thanks!
Here is the code:
$(document).ready(function() {
var refreshRate = 5000;
var autoRefresh = setInterval(
function () // Call out to get the time
{
$.ajax({
type: 'GET',
success: function(data){
document.getElementById('data').innerHTML=data;
var blink = setInterval (function () {
var blink_cell = $("#blink_div").html();
if (blink_cell > 0) {
$("#blink_div").toggleClass("blink");
} else {
$("#blink_div").addClass("invisible");
}
},500);
} // end success
}); // end ajax call
}, refreshRate);// end check
}); // end ready
Be concerned with the scope of your variables and clear the blink intervall before initiating a new one.
$(document).ready(function() {
var refreshRate = 5000;
var blink = -1;
var autoRefresh = setInterval(
function () // Call out to get the time
{
$.ajax({
type: 'GET',
success: function(data){
document.getElementById('data').innerHTML=data;
if(blink>-1) clearInterval(blink);
blink = setInterval (function () {
var blink_cell = $("#blink_div").html();
if (blink_cell > 0) {
$("#blink_div").toggleClass("blink");
} else {
$("#blink_div").addClass("invisible");
}
},500);
} // end success
}); // end ajax call
}, refreshRate);// end check
}); // end ready
$(document).ready(function () {
var _url = ''; // Put your URL here.
var _checkServerTime = 5000;
var _blinkTime = 500;
function _blink() {
// Do something here.
var condition = true; // Put condition here.
if (condition) setTimeout(_blink, _blinkTime);
}
function _handleData(data) {
$('#data').html(data);
_blink();
}
function _checkServer() {
$.get(_url, _handleData);
}
setInterval(_checkServer, _checkServerTime);
});
So I have an interval I create for each of my posts, the issue is that I load new posts and remove the old ones, so obviously I'd like to stop the interval for the previous posts. However I can't seem to figure out how to do this. Could someone explain to me how to properly go about doing this? I'm completely lost.
$(".post").each(function(){
myInterval = setInterval("postStats('"+$(this).attr('id')+"')", 500);
});
function postStats(pid) {
//do some stuff
}
$(".button").click(function(){
clearInterval(myInterval);
});
You can store the interval ID in a data attribute:
$(".post").each(function () {
var that = this;
var myInterval = setInterval(function () {
postStats(that.id);
}, 500);
$(this).data("i", myInterval);
});
and clear the interval specific to each .post like so:
$(".button").click(function () {
// assuming the button is inside a post
clearInterval($(this).closest(".post").data("i"));
});
and like SiGanteng said, you should pass a function object to setInterval rather than a string, which only gets eval'd.
You need to keep one handle for each interval that you start:
var myIntervals = [];
$(".post").each(function(){
var id = $(this).attr('id');
var handle = window.setInterval(function(){
postStats(id);
}, 500);
myIntervals.push(handle);
});
function postStats(pid) {
//do some stuff
}
$(".button").click(function(){
$.each(myIntervals, function(i, val){
window.clearInterval(val);
});
myIntervals = [];
});