Refresh div only with server time rather than JS - javascript

I'm not sure if this is possible or not, but I am able to somehow have my div refresh in server seconds rather a jquery timer?
Or possibly to not have the timer start until all images have loaded?
This method works however it goes out of sync quite often, possibly because of some images still trying to load.
This code was sourced online
Markup:
refreshing in <div id="countDown"></div>
Refresh div after 10 seconds:
$(document).ready( function(){
$(' #avatars').load(' #avatars');
refresh();
});
function refresh()
{
setTimeout( function() {
$(' #avatars').load(' #avatars');
refresh();
}, 10000);
}
Jquery 15sec timer, resets back to 15 after 0
window.onload = function() {
startCountDown(10, 1000, myFunction);
}
function startCountDown(i, p, f) {
var pause = p;
var fn = f;
var countDownObj = document.getElementById("countDown");
countDownObj.count = function(i) {
// write out count
countDownObj.innerHTML = i;
if (i == 0) {
// execute function
fn();
startCountDown(10, 1000, myFunction);
// stop
return;
}
setTimeout(function() {
// repeat
countDownObj.count(i - 1);
}, pause);
}
// set it going
countDownObj.count(i);
}
function myFunction(){};

If you just want to delay the timer until your image loads couldn't you use the callback function on $('#avatars').load('#avatars'); to start the timer?
function refresh(){
$('#avatars').load('#avatars', function(){
setTimeout(function(){
refresh();
}, 10000);
startCountDown(10, 1000, myFunction);
});
}
I believe that this wouldn't start the count down until the images finish loading.

Call refresh function when load status is success.See for more in here http://api.jquery.com/load/
$("#avatars").load(url, function(responseTxt, statusTxt, xhr) {
// debugger;
if (statusTxt == "success")
{
refresh();
}
if (statusTxt == "error")
{
console.log("Error: " + xhr.status + ": " + xhr.statusText);
}
});

Related

Javascript Countdown Timer w/ Bootstrap Modal Pause

See my code below, I am trying to get the countdown timer to pause when a bs.modal is shown and to resume again once the modal is hidden. This works perfectly if the modal is opened and then closed but if you try to reopen the modal again, the timer just continues. I am probably missing something obvious but am not the best when it comes to JS.
(function countdown(remaining) {
if(remaining === 0) {
location.reload(true);
}
document.getElementById('countdown').innerHTML = remaining;
$(document).on('shown.bs.modal', function(e) {
console.log("modal triggered");
clearTimeout(timeout);
});
$(document).on('hide.bs.modal', function(e) {
console.log("modal closed");
countdown(remaining - 1);
});
timeout = setTimeout(function(){
if(remaining != 0) {
countdown(remaining - 1);
}
}, 1000);
})(300);
It seems the issue with the existing code is a timing problem that results in multiple timeouts getting set simultaneously, some of which can then never be cleared because their id's get lost. It's easy to get into such a situation when you're setting up a new timeout for every iteration. So, as I mentioned, setInterval() is a better choice here. Below is a solution using setInterval(). Also note that it's written so as to ensure that any existing interval is cleared before its id is overwritten (in the function clearAndSetInterval.)
(function (remaining) {
var interval;
var clearAndSetInterval = function () {
clearInterval(interval);
interval = setInterval(function (){
if (remaining <= 0) {
clearInterval(interval);
location.reload(true);
}
document.getElementById('countdown').innerHTML = remaining;
remaining = remaining - 1;
}, 1000);
};
$(document).on('shown.bs.modal', function(e) {
clearInterval(interval);
});
$(document).on('hide.bs.modal', function (e) {
clearAndSetInterval();
});
clearAndSetInterval();
})(300);

How to load different pages in interval every minute using javascript?

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++;
};
});

Wait for a URL to download all the contents of a webpage

I have to download HTML Content of a URL. The problem is that the URL takes some time to load , so I have to wait/ timeout for sometime ( ~10 - 15 secs) before logging the content. To achieve this, I tried 2 approaches, but all of them fail to produce the desired result.
First approach is the use of setTimeOut:
var page = require('webpage').create()
page.open(url, function (status) {
if (status !== 'success') {
console.log('Unable to load the address!');
phantom.exit();
} else {
window.setTimeout(function () {
console.log(page.content);
phantom.exit();
}, 10000);
}
});
But setTimeout fails to set the specified timeout. No matter what value I put as Timeout , it times out after a fixed amount of time which is less than the page load time.
The second approach was the use of OnLoadFinished:
var page = new WebPage(), testindex = 0, loadInProgress = false;
page.onConsoleMessage = function(msg) {
console.log(msg)
};
page.onLoadStarted = function() {
loadInProgress = true;
console.log("load started");
};
page.onLoadFinished = function() {
loadInProgress = false;
console.log("load finished");
};
var steps = [
function() {
page.open("url");
},
function() {
console.log(page.content);
}
];
interval = setInterval(function() {
if (!loadInProgress && typeof steps[testindex] == "function") {
console.log("step " + (testindex + 1));
steps[testindex]();
testindex++;
}
if (typeof steps[testindex] != "function") {
console.log("test complete!");
phantom.exit();
}
}, 5000);
In this approach, OnLoadFinished fires before the full page is loaded.
I am new to phantomJS , so the above two solutions are also from stack overflow. Is there something I am missing that is particular to my case ? Is there any other way to achieve the same result? ( I tried Waitfor construct also, but with no success).
Ok, you problem is to load Content after some timeout. If you are looking for DOM element, you have to use known to you WaitFor function. But if you just want to get page content after timeout, it is so much easier. So lets start.
var page = require("webpage").create();
var address = "http://someadress.com/somepath/somearticle";
var timeout = 10*1000;
page.open(address);
function getContent() {
return page.evaluate(function() {
return document.body.innerHTML;
});
}
page.onLoadFinished = function () {
setTimeout(function() {
console.log(getContent());
}, timeout);
}
Note! If you are waiting for large content in HTML body, use setInterval function, to wait for document.body.innerHTML more than you want.

jQuery timeout function to run if a user is inactive

I've got a jQuery timeout script that runs after 30 minutes, however, it is constantly running and I only want it to run if the user has been inactive for that amount of time. How do I go about doing this?
$(function(){
var timeout = 30000;
$(document).on("mousemove", function(){
clearTimeout(timeout);
})
setTimeout(function(){
$.post("../php/logout.php", {}, function(response){
if(response.success == "1"){
location.replace("../pages/timed_out.php");
}
}, "json");
}, timeout);
})
You should reset timeout by clearing it using timeout's ID (which can be obtained as setTimeout function result) in clearTimeout and setting timeout again:
$(function()
{
var timeout = 30000;
var timer = 0;
setTimer();
$(document).on("mousemove", function()
{
clearTimeout(timer);
setTimer();
});
function setTimer()
{
timer = setTimeout(function()
{
$.post("../php/logout.php", {}, function(response)
{
if (response.success == "1")
{
location.replace("../pages/timed_out.php");
}
}, "json");
}, timeout);
}
});
If you want to reset the 'timeout', then just changing the timeout variable won't do anything. You would need to actually clear the timeout using clearTimeout()
To do this, here is what you'd need to do...
function restartTimeout() {
timeoutHolder = setTimeout(function(){
$.post("../php/logout.php", {}, function(response){
if(response.success == "1"){
location.replace("../pages/timed_out.php");
}
}, "json");
}, 30000);
}
$(function(){
$(document).on("mousemove", function(){
clearTimeout(timeoutHolder);
restartTimeout();
})
restartTimeout();
})
Take note of the fact that I assigned a variable to 'hold' the setTimeout() as that is necessary to be able to clear it.

Pause in middle of javascript function

I am trying to pause in the middle of a function for a given period of time (5 secs)
this is what I tried, but It doesn't work
(function MessagesAjax() {
$.post('/api/messages/get', function(data) {
for (var i = 0; i < data.length; i++) {
$.jGrowl(data[i].Body.toString().substring(0, 150), { header: 'New Message', sticky: true, });
markDisplayed(data[i].Id);
}
setTimeout(MessagesAjax, 5000);
});
})();
function markDisplayed(id) {
setTimeout(5000); //want it to pause here
$.post("/api/messages/markdisplayed" + id);
console.log("Marking displayed");
}
I just need it to pause so there is a delay before the post is sent back to the server
I'm almost sure that setTimeout is not what I want, but I'm not sure what else to use
Change markDisplayed to:
function markDisplayed(id) {
setTimeout(function() {
$.post("/api/messages/markdisplayed" + id);
console.log("Marking displayed");
}, 5000);
}​
This will cause the function to wait for five seconds before executing the content within it.
replacing
function markDisplayed(id) {
setTimeout(5000); //want it to pause here
$.post("/api/messages/markdisplayed" + id);
console.log("Marking displayed");
}
with
function markDisplayed(id) {
setTimeout(function(){
$.post("/api/messages/markdisplayed" + id);
console.log("Marking displayed");
},5000); //want it to pause here
}
may work for you.

Categories