I'm a PLC programmer, i made a html page and i need it script refresh every second, so in my body i placed:
<body onload="changeimage()">
.... code ....
</body>
And the script:
<script>
setInterval(function changeimage() {
var sonde = ["Sonda1","Sonda2","Sonda3","Sonda4"];
var tsonde = ["tsonda1","tsonda2","tsonda3","tsonda4"];
var temperature = [:="OUTPUT".AlarmTemp.Sonda1:,:="OUTPUT".AlarmTemp.Sonda2:,:="OUTPUT".AlarmTemp.Sonda3:,:="OUTPUT".AlarmTemp.Sonda4:];
var hotcold = document.getElementById("Fiocco");
if (:="OUTPUT".Stagione.Estate: > 0){
hotcold.src="sun.jpg"}
if (:="OUTPUT".Stagione.Inverno: > 0){
hotcold.src="Neve.png"}
for (x in temperature) {
var icona = document.getElementById(sonde[x]);
if (temperature[x] > 0 ){
icona.src="Paverde.png"
}
else{
icona.src="Parossa.png"
}
}
}, 1000);
</script>
Anyway i get the error:
ReferenceError: changeimage is not defined
P.S.: Don't get fooled by the arrays who start with ":", is a PLC syntax, is correct.
# Even removing the setinterval option, the script is not working.
Define the function first and make sure the script is loaded.
Example in code pen: https://codepen.io/mikila85/pen/NWPvQPE
function changeimage() {
setInterval(function() {
var sonde = ["Sonda1","Sonda2","Sonda3","Sonda4"];
var tsonde = ["tsonda1","tsonda2","tsonda3","tsonda4"];
var temperature = [:="OUTPUT".AlarmTemp.Sonda1:,:="OUTPUT".AlarmTemp.Sonda2:,:="OUTPUT".AlarmTemp.Sonda3:,:="OUTPUT".AlarmTemp.Sonda4:];
var hotcold = document.getElementById("Fiocco");
if (:="OUTPUT".Stagione.Estate: > 0){
hotcold.src="sun.jpg"
}
if (:="OUTPUT".Stagione.Inverno: > 0){
hotcold.src="Neve.png"
}
for (x in temperature) {
var icona = document.getElementById(sonde[x]);
if (temperature[x] > 0 ){
icona.src="Paverde.png"
}
else{
icona.src="Parossa.png"
}
}
}, 1000);
}
Anyway i get the error: ReferenceError: changeimage is not defined
setInterval(function changeimage() {
Sure it won't be defined, as it was only defined as a callback function to the setInterval() call.
So it won't be visible outside of this setInterval scope, and it won't be visible for the onload event listener of your body.
Solution:
You should define your changeimage() function in the global scope (outside of the setInterval like this:
<head>
<script>
function changeimage() {
var sonde = ["Sonda1", "Sonda2", "Sonda3", "Sonda4"];
var tsonde = ["tsonda1", "tsonda2", "tsonda3", "tsonda4"];
var temperature = [: = "OUTPUT".AlarmTemp.Sonda1: ,: = "OUTPUT".AlarmTemp.Sonda2: ,: = "OUTPUT".AlarmTemp.Sonda3: ,: = "OUTPUT".AlarmTemp.Sonda4: ];
var hotcold = document.getElementById("Fiocco");
if (: = "OUTPUT".Stagione.Estate: > 0) {
hotcold.src = "sun.jpg"
}
if (: = "OUTPUT".Stagione.Inverno: > 0) {
hotcold.src = "Neve.png"
}
for (x in temperature) {
var icona = document.getElementById(sonde[x]);
if (temperature[x] > 0) {
icona.src = "Paverde.png"
} else {
icona.src = "Parossa.png"
}
}
}
setInterval(changeimage(), 1000);
</script>
</head>
<body onload="changeimage()">
.... code ....
</body>
You can see it working in this Demo.
Note:
Make sure to place your script tag in the head of your HTML page before the body tag so it can be accessed in the onload event listener.
try this
function changeImage(){
....
}
// if you need to call every 1 sec
setInterval(changeImage,1000);
// else
changeImage(); or // setTimeout(changeImage,1000)
Related
I am wondering why this code is working in a project for itself but as soon as i add a window.addEventListner("load") function it stops working.
Original working code
<html>
<head>
<meta charset="UTF-8">
<title>Hello</title>
</head>
<body>
<button id="click">Click</button>
</body>
</html>
<script>
var count = 0;
var timeout;
function test() {
console.log(count);
count = count + 1;
timeout = setTimeout("test()", 1000);
}
document.getElementById("click").addEventListener("click", function (e) {
test();
}, false);
</script>
Modified Javascript code which gives me this error 'ReferenceError: test is not defined.
window.addEventListener('load', function () {
var count = 0;
var timeout;
function test() {
console.log(count);
count = count + 1;
timeout = setTimeout("test()", 1000);
}
document.getElementById("click").addEventListener("click", function (e) {
test();
}, false);
}
finally,i know what you mean ,try to run this on your console:
var site = "global";
function foo() {
var site = "partial";
setTimeout('alert(site);', 100);
}
foo();
ok,tell me ,what do you got ? partial or global?
sorry,it is 'global'!
that is because,string in the setTimeout(the first argument ) is executed in the global scope,so when the 'alert(site)' executing , it will find
var site = "global";
and will never find
var site = "partial";
because this site is in the function foo scope,in general,we can't visit variable defined in the function scope out of the function except closure.
in this case,we can not visit variable site defined in the foo in the global scope.
so,if you don't define site in the global ,you will get the error ,for example:
var s = "global";
function foo() {
var site = "partial";
setTimeout('alert(site);', 100);
}
foo();
what do you got ?
Uncaught ReferenceError: site is not defined
that is exactly why you got error after you add a window.addEventListner("load") function.Now,pay attention to the following codes ,especially comments.
<script>
// when you visit function test in the setTimeout,you visit it here!
// you didn't define another function test in the global,
//if you defined,it will execute this function test
window.addEventListener('load', function () {
var count = 0;
var timeout;
function test() {
console.log(count);
count = count + 1;
timeout = setTimeout("test()", 1000);
// you can't visit function test in the global,because function test is defined in this anonymous function
}
document.getElementById("click").addEventListener("click", function (e) {
test();
}, false);
});
</script>
keep going ,see this
<html>
<head>
<meta charset="UTF-8">
<title>Hello</title>
</head>
<body>
<button id="click">Click</button>
</body>
</html>
<script>
function test() {
console.log('in the global')
};
window.addEventListener('load', function() {
var count = 0;
var timeout;
function test() {
console.log(count);
count = count + 1;
timeout = setTimeout("test()", 1000);
}
document.getElementById("click").addEventListener("click", function(e) {
test();
}, false);
});
</script>
what do you got ?
0
in the global
so,i guess you understand now,we are going to talk about how to fix the problem,just remove the "" or '' and (),use the function name is fine.
timeout = setTimeout(test, 1000);
this will make it execute normally.actually,we do not use the following type,
timeout = setTimeout("test()", 1000);
due to historical reasons,you can stil see this kind of code ,but we don't suggest,and it will consume performance,that's all,hope you understand.
There is a syntax error, closing ) is missing
window.addEventListener('load', function() {
var count = 0;
var timeout;
function test() {
console.log(count);
count = count + 1;
timeout = setTimeout(test, 1000); //observe this change as well.
}
document.getElementById("click").addEventListener("click", function(e) {
test();
}, false);
}); //this final `)` was missing
Demo
window.addEventListener('load', function() {
var count = 0;
var timeout;
function test() {
console.log(count);
count = count + 1;
timeout = setTimeout(test, 1000);
}
document.getElementById("click").addEventListener("click", function(e) {
test();
}, false);
});
<button id="click">Click</button>
Note
Following line in your code
timeout = setTimeout("test()", 1000);
causes
"message": "Script error."
Hence has been changed to
timeout = setTimeout(test, 1000);
I am currently setting up two buttons, start and stop for a jquery loop on html5. The start button works perfectly but whatever I try the 'stop' button remains inactive. I have seen many examples about stopping the loop but none seems to resolve the issue in the button being unresponsive. Sorry if this is such a simple question, but as a student I am quite frustrated and thus asking. cheers
"use strict";
var current_banner_num = 1;
$(document).ready(function(){
$("#banner-base").css("visibility","hidden");
$("#banner-"+current_banner_num).show();
var next_button = $("#start").button();
var stop_button = $("#stop").button();
next_button.click(function(){
var timer = setInterval(myCode, 2000);
function myCode() {
//$("#banner-"+current_banner_num).hide();
$("#banner-"+current_banner_num).fadeTo(800, 0);
if (current_banner_num == 4) {
current_banner_num = 1;
}
else {
current_banner_num++;
}
$("#banner-"+current_banner_num).fadeTo(800, 1);
}
});
stop_button.click(function(){
function abortTimer(){
clearInterval(timer);
}
});
});
You are just defining a function again and again here. Just get rid of the function in the event handler:
stop_button.click(function(){
clearInterval(timer);
});
This would execute the clearInterval(), while the code in your original question just defines a function, but doesn't call or do anything as you said. Hope it gets solved.
I think you have 2 problems in your code. timer variable is not visible outside of next_button.click(function(){ ... }); because it is local for this function, so you need to make it a little bit global; second problem is that in stop_button.click(function(){ ... }); you just declare function abortTimer but do not call it (in general, it is not necessary to declare that function). I think your code should be like:
"use strict";
var current_banner_num = 1;
$(document).ready(function(){
$("#banner-base").css("visibility","hidden");
$("#banner-"+current_banner_num).show();
var next_button = $("#start").button();
var stop_button = $("#stop").button();
var timer = null;
next_button.click(function(){
timer = setInterval(function(){
//$("#banner-"+current_banner_num).hide();
$("#banner-"+current_banner_num).fadeTo(800, 0);
if (current_banner_num == 4) {
current_banner_num = 1;
}
else {
current_banner_num++;
}
$("#banner-"+current_banner_num).fadeTo(800, 1);
}, 2000);
});
stop_button.click(function(){
clearInterval(timer);
});
});
Also it wasn't necessary to declare function myCode in nextButton function, so i clear it too for you
Use a global variable instead of a local one ,unwrap the clearInterval function
"use strict";
var current_banner_num = 1;
$(document).ready(function(){
$("#banner-base").css("visibility","hidden");
$("#banner-"+current_banner_num).show();
var next_button = $("#start").button();
var stop_button = $("#stop").button();
var timer = null;
next_button.click(function(){
timer = setInterval(myCode, 2000);
function myCode() {
//$("#banner-"+current_banner_num).hide();
$("#banner-"+current_banner_num).fadeTo(800, 0);
if (current_banner_num == 4) {
current_banner_num = 1;
}
else {
current_banner_num++;
}
$("#banner-"+current_banner_num).fadeTo(800, 1);
}
});
stop_button.click(function(){
clearInterval(timer);
});
});
I was working on a Timer code and its working fine but I'm unable to trigger on button click. I believe there is a silly mistake that I'm not able to figure out and was looking for help.
When I click on button, I get following error in console.
Uncaught ReferenceError: startTimer is not defined
I even have tried using $(document).ready() and defined functions in it still no luck.
Code
function timer(){
var time = {
sec:00,
min:00,
hr:00
}
var max = 59;
var interval = null;
function update(str){
time[str]++;
time[str] = time[str]%60;
if(time[str] == 0){
str == "sec"? update("min"):update("hr");
}
print(str);
}
function print(str){
var _time = time[str].toString().length == 1?"0" + time[str]:time[str];
document.getElementById("lbl"+str).innerText = _time;
}
function initInterval(){
interval = setInterval(function(){
update("sec");
},1000);
}
function stopTimer(){
clearInterval(interval);
}
return {
'init': initInterval,
'stop': stopTimer
}
};
var time = new timer();
function startTimer(){
time.init();
}
function endTimer(){
time.stop();
}
<div>
<span id="lblhr">00</span>
: <span id="lblmin">00</span>
: <span id="lblsec">00</span>
</div>
<button onclick="startTimer()">Start</button>
<button onclick="endTimer()">Stop</button>
I'm looking for pure JS solution, and not JQuery($(btnId).on("click")).
Link to JSFiddle
As I mentioned in a comment, using innerText won't work in most browsers, use innerHTML. This should work:
function timer(){
var time = {
sec:00,
min:00,
hr:00
}
var max = 59;
var interval = null;
function update(str){
time[str]++;
time[str] = time[str]%60;
if(time[str] == 0){
str == "sec"? update("min"):update("hr");
}
print(str);
}
function print(str){
var _time = time[str].toString().length == 1?"0" + time[str]:time[str];
document.getElementById("lbl"+str).innerHTML = _time;
}
function initInterval(){
interval = setInterval(function(){
update("sec");
},1000);
}
function stopTimer(){
clearInterval(interval);
}
return {
'init': initInterval,
'stop': stopTimer
}
};
var time = new timer();
function startTimer(){
time.init();
}
function endTimer(){
time.stop();
}
<div>
<span id="lblhr">00</span>
: <span id="lblmin">00</span>
: <span id="lblsec">00</span>
</div>
<button onclick="startTimer()">Start</button>
<button onclick="endTimer()">Stop</button>
So, your jsfiddle doesn't work because jsfiddle isn't expecting you to assign the onclick event in the HTML section.
You need to migrate that to the javascript section. In the HTML you need to assign an id to each button. Then, in the javascript section, have something like
document.getElementById("bStart").onclick = startTimer;
I also noticed that you have startTimer_out() as a function, but your HTML is trying to call startTimer().
Looks like it may just a jsfiddle thing.
in this index page of index-customer.php
i put this javascript at the end of the head tag of index-customer.php but it does not seem to work. is it because i did not call the function of the javascript. please help me ! thank you !
<script type ="text/javascript">
var timer = 0;
function set_interval() {
timer = setInterval("auto_logout()", 2);
}
function reset_interval() {
if (timer != 0) {
clearInterval(timer);
timer = 0;
timer = setInterval("auto_logout()", 2);
}
}
function auto_logout() {
window.location = "Logout.php";
}
</script>
First argument of setInterval should be name of the function, not the function call itself. Use timer = setInterval(auto_logout, 2000) instead
And no Quotes around function name.
I'm wanting to know how to put a message in every time the timer starts over. And here is my code thus far:
<head>
<script type="text/javascript">
var c=10;
var t;
var timer_is_on=0;
function timedCount() {
document.getElementById('txt').value = c;
c = c - 1;
if (c == 0)
c = 10;
}
function doMining() {
if (!timer_is_on) {
timer_is_on = true;
t = setInterval(function () {
timedCount();
}, 1000);
}
}
</script>
<SPAN STYLE="float:left">
<form>
<input type="button" value="Mining" onClick="doMining()">
<input type="text" id="txt">
</form>
</SPAN>
2 easy steps:
Create a place for your message to show up (i.e. another web element)
In your conditional, when your counter reaches 0, update the message element's value
Here's an example:
<div id='message'></div>
Then, access that element and append your message or modify your method using DOM traversal (preferably using a javascript framework such as dojo or jquery but you can also do it manually):
if (c == 0) {
var _message = document.createTextNode("Timer has finished!");
document.getElementById('message').appendChild(_message);
c = 10;
}
Also, don't put a SPAN around a form. Try a "div" instead. Span's are meant for styling in-line document elements.
Edit: I'm assuming when you say "start over" you mean when the c = 0 or the timer has run 10 times. When it "starts over" could also mean when the method is re-called by the timer (i.e. every 1 second, in which case you'd just put the update code at the top of the function)
You are already catching this event in your "if (c == 0)". Just add the extra code you need there?
You need to better define what it means to start over. Try pulling it out into its own method so you can work with it separately.
<script type="text/javascript">
var c=10;
var t;
var timer_is_on=0;
function timedCount() {
document.getElementById('txt').value = c;
c = c - 1;
if (c == 0)
startOver();
}
function startOver() {
alert("Starting Over, Fool!");
c = 10;
clearTimeout(t);
timer_is_on=0;
doMining();
}
function doMining() {
if (!timer_is_on) {
timer_is_on = true;
t = setInterval(function () {
timedCount();
}, 1000);
}
}
</script>