Update DIV and empty it again 1 second later using setTimeout - javascript

I'm having a few issues with the script below.
To explain the background, the full script gets data from a JSON feed and if it has been updated since the last check it changes a marker on a map and adds a line to an array called updata[], which is straightforward enough.
Once the JSON refresh is complete I then want to display a notification of each refreshed item inside a small notifiation div at the bottom of the screen for 1 second before disappearing. The process should repeat until updata[] is empty.
Any ideas what I'm doing wrong?
<script type='text/javascript'>
//updata[] is populated by JSON in the full version, but for now...
var updata=["Site A Updated at 00:20"," Site B Updated at 00:22"," Site C Updated at 00:24"];
var val=0;
var max=updata.length+1;
function addtodiv()
{
document.getElementById('alarms').innerHTML = '<span>'+window.val+':'+window.updata[window.val]+'</span>'
setTimeout(cleardiv(), 1000); // refresh in 1 secs
}
function cleardiv()
{
window.val++;
document.getElementById('alarms').innerHTML = '<span> </span>'
if (window.val==window.max)
{
window.val=0;
window.updata=[];
} else {
setTimeout(addtodiv(), 200); // refresh in 0.2 secs
}
}
addtodiv();
</script>

setTimeout accepts function reference as the first argument. So change your code:
setTimeout(cleardiv(), 1000);
to this:
setTimeout(cleardiv, 1000);
...
setTimeout(addtodiv, 200);
You don't want to invoke functions immediately cleardiv(), you just need to provide a reference.

Related

jQuery code should change something simple in web page by using JSON data from two external device buttons

This is my school project. I have tried to do it as simple as possible, just to change background color in web page etc..
I work with an external device with two buttons (microbit a and b) -connected in serial port, writing data string "aa" or "bb". Then python code reads it inside for ever loop and writes it in json file, where this code should be able to enter in. With these changing json time stamps, this code should read which button was pressed latest and then do what is written in conditions.
json files reference time is changing all the time, by the button press.
I am very thankful for any help, we have been doing this project already quite long, this is final stage but as you see ,but i am not yet there.
As this does not execute anything after get json line... it did once, and till final >>if, but then it stopped..why? I dont know.. I am not good enough in this.
Final part of the code curly braces etc, i cant anymore count which one is too much or >>what is missing?! ...
my json example: {"REF": 1624391142, "aa": 1624391140, "bb": 1624391142}
$(document).ready(function () {
console.log("jQuery starts");
var d = new Date();
var time = d.getTime();
setInterval(function () {
// loop that reads every 2 sec json file,
$.getJSON("data.json"),
function (json) {
console.log("test", time);
//what is REF-time <= time
if (time <= json.REF) {
// any changes?
time = json.REF;
console.log(" REF", time);
pressedBtn = "";
jQuery.each(json, function (key, value) {
//searhing
if (value == time && key != "REF") {
pressed = key;
console.log("Working");
}
if (pressedBtn == "aa") {
$("body").show("active"); //background color change
console.log("pressed", pressedBtn);
$("#toshow").show("toshow"); // comment div
}
if (pressedBtn == "bb") {
$("#toshow").hide("toshow"); //comment div
console.log("pressed", pressedBtn);
}
});
}
};
}, 2000);
});
I think I understood you and maybe this is your solution check this
$(document).ready(function(){
setTimeout(doSomething,2000);
});
function doSomething(){
console.log("do something");
setTimeout(doSomething,2000);
}
this function is execute every 2 seconds like you want in your code
i hope i have help you
Ok, here is a pick what was wrong. I somehow had added parenthes there right side of the json, where is shouldnt be, thats how the whole block got stuck, i am appologising for taking anyones time. All these marks and syntaxes make one crazy..
Thank you anyway, this community is amazing

Knockout setTimeout delay

When a user logs into my website, I store a "logged in until" parameter on my server for that user, which is updated each time they interact with the server. So if they are inactive for X seconds, they should be logged out and the page on their client refreshed to show the login screen. Everything works nicely except the function keeps calling itself at 1 second intervals, and not the 1700+ second interval I'm looking for. As each call hits the server, I don't want this to keep running more often than it needs to.
This function is contained within my knockout viewmodel. logoutTimer is declared as a global variable. Watching the console log I can see the delay shows the correct time, but it seems to be running about every 1 second.
self.autoLoginCheck = function() {
clearTimeout(logoutTimer);
//If not, refresh the main screen => that'll push them to the login screen automatically
myurl = "/api/checkLoginStatus.php";
var parameters = {
'userPublicID':self.userInfo().userPublicID
}
$.post(myurl, parameters, function(data) {
var getResponse = JSON.parse(data);
if (getResponse.loggedIn < 1 ) {
//This is the log out condition
location.reload(true);
} else {
//Check how many more seconds the current log in is good for, that's when we'll check it again
var msdelay = getResponse.nextCheck * 1000;
console.log("Delay is " + msdelay);
logoutTimer = setTimeout(self.autoLoginCheck(), msdelay);
}
});
}
I know this type of question has been asked many times, but reading all those answers I can't see why this function is running every second and not waiting 30 minutes. Thanks to whoever shows me the obvious!
The first parameter to setTimeout should be a function, not the result of a function.
logoutTimer = setTimeout(self.autoLoginCheck, msdelay);

Javascript executing button click on page event

I'm new to javascript, and I'm trying to see if what I want to do is possible. I want to take a current webpage that I have open in my browser, and execute new javascript. There is a timer on this page, and when it increases to a particular time, I want it to execute a button click.
This would be the time that is changing and that I want to add into a if statement:
07:34:04
Will this changing time raise an event that would cause a javascript to run? I want something along the lines of:
if time = 7:35:00 then click button.
Thanks for your help!
I'll like to make a contribution..
I don't know much about the javascript time format, but I'll post back if I can look it up.
Any way you can use a function such as this:
var waiter;
function waitForTimer(extime, fn)
{
//Here, fn is the function to be executed..
//While extime is the time at which the function is to be executed..
waiter = setInterval(function(fn,extime){
//this function will check every one second..
if( extime == time )
{
fn();
clearInterval(waiter);
}
else
log("waiting for " + time);
}, 1000);
}
I hope this helps.

Wait to execute code until after AJAX called image renders

I am trying to run some code that grabs the width and height of a div after it is loaded and filled with an image from an AJAX call.
The div is 0x0 until the image is placed so checking the dimensions before pretty much breaks everything.
I have tried .load() (Doesn't work because this is an AJAX call). I also tried the imagesLoaded js plugin. Here is what I have right now:
alert('outside;')
function startBubbles(){
alert('inside');
var space = new DisplaySpace($('#bubbleWrap').height(), $('#bubbleWrap').width());
var count = 1;
alert(space.getHeight());
var delay = (function(){
var timer = 0;
return function(afterResize, ms){
clearTimeout (timer);
timer = setTimeout(afterResize, ms);
};
})();
var spawnInterval = self.setInterval(function(){
var aBubble = new Bubble(count, space);
count++
aBubble.spawnimate(aBubble);
setTimeout(function() {aBubble.popBubble(aBubble)},Math.floor((Math.random()*30000)+10000));
}, 500);
});
My alerts all fire before the image is visible, then my 'space' object still has height and width of 0.
bubbleWrap is a div inside the loading zone that contains the image in question. I realize I could probably but a manual delay in here to solve the problem MOST of the time - however that doesn't seem optimal. What am I missing?
I'm now implementing the load of this particular state like this:
History.Adapter.bind(window,'popstate',function(){
var state = History.getState();
state = 'target='+state.data.state;
$.get('contents.php', state, function(data){
if(state == 'target=bubbles'){
$('#loading_zone').html(data).waitForImages(startBubbles());
}
else{
$('#loading_zone').html(data);
}
});
});
Unfortunately, on page reload, the height ends up as only 10. Everything seems great when I just navigate away and come back, though. Any thoughts?
I have a plugin that could do this nicely.
Simply call it after you inject the new HTML.
// Assume this function is the callback to the *success*.
function(html) {
$("#target").html(html).waitForImages(function() {
// All descendent images have now loaded, and the
// containing div will have the correct dimensions.
});
};

How to check the status each 10 seconds with JavaScript?

I have a server (mysite.com/status), which returns number of active tasks (just a single integer).
How can I check number of active tasks each 10 seconds with JavaScript and show user something like:
Number of remaining tasks: XXX
And, if number of tasks is 0, then I should load another page.
Make a function set a new timeout calling itself.
function checkTasks(){
// Make AJAX request
setTimeout(checkTasks, 10000);
}
checkTasks(); // Start task checking
with jQuery for AJAX functions... (untested code)
setInterval(function(){
$.get('http://example.com/status',function(d){
// where there is html element with id 'status' to contain message
$('#status').text('Number of remaining tasks: '+d)
if(d == 0){
window.location = '/another/page'
}
})
},10000)
I have thought of different approach, without any AJAX. As you just need to show simple plain data, just use <iframe> to show that dynamic data then with simple JS "reload" the frame every 10 seconds.
HTML would be:
Number of remaining tasks: <iframe id="myFrame" src="mysite.com/status"></iframe>
And the JavaScript:
window.onload = function() {
window.setTimeout(ReloadTime, 10000);
};
function ReloadTime() {
var oFrame = document.getElementById("myFrame");
oFrame.src = oFrame.src;
window.setTimeout(ReloadTime, 10000);
}
Live test case, using time for the same of example.
With some CSS you can make the frame look like part of the text, just set fixed width and height and remove the borders.
setInterval(function(elem){ // here elem is the element node where you want to display the message
var status=checkStatus(); // supposing that the function which returns status is called checkStatus
if(status == 0){
window.location = '/another/page'
}
else {
elem.innerHTML="Number of remaining tasks:"+status;
}
},10000)
Using the javascript library jquery, you can set a repeating infinite loop.
That gets the data from a page and then sets the inner html of an element.
http://jsfiddle.net/cY6wX/14/
This code is untested
edit: demonstration updated
Also I did not use the jquery selector for setting the value in case you do not want to use jquery.

Categories

Resources