<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
window.onload = setupRefresh;
function setupRefresh()
{
setInterval("refreshBlock();",3000);
}
function refreshBlock()
{
$('#time').load("Callgen1.html");
}
</script>
I am stuck and wanted the div to reload after every 3 seconds. Any answer would be helpful.
Thanks in advance.
I have made few changes to your question, you need to pass reference to the function rather then string object in setInterval method.
please refer below answer, it will reload your div every 3 seconds, you can put your load method in place of my code "$('#time').html(new Date());" to solve your purpose
*{color:white;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
function setupRefresh()
{
setInterval(refreshBlock,3000);
}
setupRefresh()
function refreshBlock()
{
$('#time').html(new Date());
}
</script>
<div id="time">test</div>
My guess is what you really want is to actually refresh 3 seconds after the prior one has finished so you do not pile up refreshes if it takes longer than 3 to load. I added to the delay just so you can see it is doing that.
async function delay(delayMilliseconds) {
return new Promise(resolve => {
setTimeout(() => {
resolve(timeToWait);
}, delayMilliseconds);
});
}
let timeToWait = 1000;
function redoLoad(forHowLong) {
console.log("called redoLoad: " + forHowLong);
// for fun, change the delay, then reset it again
forHowLong = timeToWait >= 5000 ? 1000 : forHowLong + 1000;
$('#time').load("Callgen1.html", function(responseText, textStatus, jqXHR) {
console.log(textStatus);
timeToWait = forHowLong;
sampleDelay(forHowLong);
});
}
async function sampleDelay(waitTime) {
console.log("before ");
let delayres = await delay(waitTime)
.then(function(v) {
redoLoad(v);
});
console.log("after:" + waitTime);
}
sampleDelay(timeToWait);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="time">howdy</div>
Related
success: function (result) {
if (result == 1) {
var auto_refresh = setInterval(function () {
$('#myDiv').fadeOut('slow', function () {
$(this).load('/echo/json/', function () {
$(this).fadeIn('slow');
});
});
}, 1025544);
}
}
Friends on success function I have to refresh the myDiv DIV only once but as the above code the DIV is keep on fade out and fade in continuously instead it should work only once
setInterval() repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. It will continue to do so until clearInterval is called.
It is easiest just to use setTimeout(), which just delays the function being called for the specified time:
var auto_refresh = setTimeout(function() {
$('#myDiv').fadeOut('slow', function() {
$(this).load('/echo/json/', function() {
$(this).fadeIn('slow');
});
});
}, 1025544);
using a variable name auto_refresh kind of indicates you want it to repeat. also -> 1025544ms = 17mins. so it will refresh every 17 mins.
if you want it to not show, wait 17mins then show, use #Jacod Grays Answer.
if you just want it to show, remove the setInterval like so :-
success: function (result) {
if (result == 1) {
$('#myDiv').fadeOut('slow', function () {
$(this).load('/echo/json/', function () {
$(this).fadeIn('slow');
});
});
}
}
I would like to hide and then show the "Reset" button as soon as the counter reaches zero.
Index.html:
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<script type="text/javascript" src="countdown.js"></script>
</head>
<body>
<input type="text" id="timer">
<script type="text/javascript">
timer = new Countdown();
timer.init();
</script>
<button id="reset">Reset</button>
<script type="text/javascript">
$("#reset").click(function(){
//timer = new Countdown();
timer.reset();
});
</script>
</body>
</html>
Please see http://jsfiddle.net/orokusaki/o4ak8wzs/1/ for countdown.js
AWolf's answer is a bit fancier than mine, and they made some good points about your code, but I tried to keep mine simple and tried not to change your original code too much.
Your init() function will now hide the Reset button, and I had the update_target() function show the Reset button when the timer expired.
Fiddle: http://jsfiddle.net/rgutierrez1014/o4ak8wzs/4/
In this jsFiddle you'll find the updated code and how you could add that behaviour.
I've also improved your code a bit. It's easier to write Countdown.prototype = { init: function() {...}, ...} then writing Countdown.prototype.init = function() {...}
I also changed your setInterval to setTimeout and start a new timeout every second. That's easier and you don't need to clear the interval at the end. Also the callback function for your interval seemed a bit strange and that probably won't work.
You could add your click handlers in the init method of your countdown object like this $('#start').click(this.start.bind(this)); the .bind(this) is used to change the context inside the click handler to the currently used object. Then this inside of the handler is your object and you can access everything with this.
To hide the reset button at start I've used the css display: none; and if you are at zero then show the button with $('#reset').fadeIn('slow'); or $('#reset').show(); if you don't want the animation.
Update 13.03.2015
As mentioned in the comments I've improved the code and now I'm using a jQuery Countdown plugin.
Please have a look at the latest version in this jsFiddle.
I think it's much better then the other code.
(function () {
function Countdown() {
this.start_time = "00:30";
this.target_id = "#timer";
//this.name = "timer";
}
Countdown.prototype = {
init: function () {
console.log('init called');
this.reset();
$('#start').click(this.start.bind(this));
$('#reset').click(this.reset.bind(this));
},
reset: function () {
time = this.start_time.split(":");
//this.minutes = parseInt(time[0]);
this.seconds = parseInt(time[1]);
this.update_target();
},
tick: function () {
if (this.seconds > 0) //|| this.minutes > 0)
{
if (this.seconds == 0) {
// this.minutes = this.minutes - 1;
this.seconds = 59
} else {
this.seconds = this.seconds - 1;
}
this.start();
}
else {
// show reset button
$('#reset').fadeIn('slow');
}
this.update_target();
},
start: function() {
console.log('start called');
//setTimeout(this.name + '.tick()', 1000);
setTimeout(this.tick.bind(this), 1000);
},
update_target: function () {
seconds = this.seconds;
if (seconds < 10) seconds = "" + seconds;
$(this.target_id).val(this.seconds);
}
};
var counter = new Countdown();
counter.init();
})();
#reset {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="timer">
<button id="start">Start</button>
<button id="reset">Reset</button>
I want to delay the appearance of an image by about 5 mins, and then once it appears I want it to disappear after 10 seconds.
I've been able to delay the appearance of an image using the code
<script type="text/javascript">
function showBuyLink() {
document.getElementById("buylink").style.visibility = "visible";
}
// adjust this as needed, 1 sec = 1000
setTimeout("showBuyLink()", 300000);
</script>
But then i'm unable to make it disappear.
This one may helps to you
function showBuyLink() {
document.getElementById("buylink").style.display = "block";
setTimeout(function (){
document.getElementById("buylink").style.display = "none";
}, 10000);
}
// adjust this as needed, 1 sec = 1000
setTimeout(showBuyLink(), 300000);
The answer is actually in your own code: setTimeout(…) is used to call a function after some time, so you can just create a second function (i.e. "hideBuyLink") and put another call to setTimeout into showBuyLink().
However, it looks as if you tried to put JavaScript onto a real site on which one shall be able to buy stuff. I advise you to contact someone to help you with the coding, since this is a beginners question, and I am afraid that you might make mistakes which could eventually be exploited by someone malicious.
Just set another timer in the show function that points to a hide function:
<script type="text/javascript">
function showBuyLink() {
document.getElementById("buylink").style.visibility = "visible";
setTimeout("hideBuyLink()", 10000);
}
function hideBuyLink() {
document.getElementById("buylink").style.visibility = "hidden";
}
// adjust this as needed, 1 sec = 1000
setTimeout("showBuyLink()", 300000);
</script>
Alternetively, if you want it in one function:
<script type="text/javascript">
function showBuyLink(){
var buyLink = document.getElementById("buylink");
if(buyLink.style.visibility == "hidden"){
buyLink.style.visibility = "visible";
setTimeout("showBuyLink()", 10000);
}else{
buyLink.style.visibility = "hidden";
}
}
// adjust this as needed, 1 sec = 1000
setTimeout("showBuyLink()", 300000);
</script>
Yet another way to do it.
setTimeout(function() {
document.getElementById("buylink").style.visibility = "visible";
setTimeout(function() {
document.getElementById("buylink").style.visibility = "hidden";
}, 10000);
},300000);
This question already has answers here:
Why is the method executed immediately when I use setTimeout?
(8 answers)
Closed 8 years ago.
i use this javascript code to open two pictures and toggle a vertical menu by clicking on another picture. an know i want to run code without clicking on image, with a timer. so i wrote this code but it run only once at first time.
what's wrong with my code?
<script type="text/javascript">
$(document).ready(function () {
$("#lista2").slideToggle(1);
$curtainopen = false;
$(".rope").click(function () {
$(this).blur();
if ($curtainopen == false) {
var selected = $(this).val();
var image = $(".rope");
image.fadeOut('fast', function () {
$("#largeImg").attr('src', 'images/power-on.png');
image.fadeIn('fast');
});
$(".leftcurtain").stop().animate({ left: '-120px' }, 2000);
$(".rightcurtain").stop().animate({ left: '120px' }, 2000);
$("#R").attr('src', 'images/Right.gif');
$("#L").attr('src', 'images/Left.gif');
$curtainopen = true;
$("#lista2").slideToggle(2000);
$(this).attr('id', '1');
} else {
var selected = $(this).val();
var image = $(".rope");
image.fadeOut('fast', function () {
$("#largeImg").attr('src', 'images/power-off.png');
image.fadeIn('fast');
});
$(".leftcurtain").stop().animate({ left: '0px' }, 2000);
$(".rightcurtain").stop().animate({ left: '0px' }, 2000);
$curtainopen = false;
$("#lista2").hide();
$(this).attr('id', '0');
}
return false;
});
});
function startTimer() {
setTimeout($(".rope").click(), 4000);
}
</script>
use this to execute your code after a specific time interval
setInterval(function() {
$(".rope").click(); // this will execute after every 4 sec.
}, 4000);
use this to execute your code after a specific time delay
setTimeout(function() {
$(".rope").click(); // this will execute after 4 sec delay only once.
}, 4000);
use above according to your requirement
setTimeout need a function, When you are passing $(".rope").click() it is called immediately.
Use it like
function startTimer() {
setTimeout(function () {
$(".rope").click();
}, 4000);
}
setTimeout(function() {
$(".rope").click();
}, 4000);
because setTimeout needs a function, but $(".rope").click() calls itself immediatly (instead of assigning a function to be called). So you don't want to call a function but to pass it to setTimeout.
A timer implies repeating the function after each timeout. setTimeOut only delays a function once (after a given time, in milliseconds).
function startTimer() {
//do your stuff
$(".rope").click();
//repeats itself after 4 seconds
setTimeout(startTimer, 4000);
}
And do not forget to start it on document ready :
$(document).ready(function () {
startTimer();
...
}
I you don't want your function to be called immediately on page load, you can add an initial delay :
$(document).ready(function () {
setTimeout(startTimer, 5000); //the timer will start only 5 seconds after page load
...
}
Can a body tag hold two set intervals? or have 2 functions use the same interval?
ex:
<body onload="setInterval(function1, 500); setInterval(function2, 1000);">
<body onload="setInterval(function1, function2, 500");>
You can create a function that calls setInterval() twice with the different functions and call it on the body.onload().
And i dont think that 2 functions can have the same interval unless you wrap them up in one or call them inline like this:
<body onload="setInterval(function(){ function1(); function2();}, 500);">
Your first example would be fine:
window.onload = function() {
setInterval(function1, 500);
setInterval(function2, 1000);
}
function function1() {
console.log("function1");
}
function function2() {
console.log("function2");
}
See an example of the above code working here.
Simply use jQuery and register an event handler (in a <script type="text/javascript"> block).
In case all you need is the DOM tree being available:
$(document).ready(function() {
setInterval(function1, 500);
setInterval(function2, 1000);
});
otherwise (if you need all images being loaded etc):
$(window).load(function() {
setInterval(function1, 500);
setInterval(function2, 1000);
});
Instantiate as many onloads as you need without the collisions.
<SCRIPT>
// Class Definition
OnLoad = function(taskFunction,miliseconds) {
var context = this;
context.cnt = 0;
context.id = null;
context.doTask=taskFunction;
context.interval = function() {
if(document.readyState == "complete"){
try{ context.stop();} catch(e){ throw new Error("stop error: " + context.id); }
try{ context.doTask();} catch(e){ throw new Error("load error: " + context.id); }
}
};
context.start = function(timing) {
if(context.id && context.id!=null)
context.stop();
context.cnt=0;
context.id=setInterval(context.interval,timing);
};
context.stop = function() {
var _id = context.id;
clearInterval(context.id);
context.id=null;
};
context.start(miliseconds ? miliseconds : 100);
};
// Example Onloads
new OnLoad(function(){
alert("onload 1");
}); // uses default timing of 100 miliseconds
new OnLoad(function(){
alert("onload 2");
},200);
new OnLoad(function(){
alert("onload 3");
},300);
</SCRIPT>
Try This Cod it's Easy.
you can run this here and TEST it.
window.onload = function() {
function foo() {
Load_Note();
}
setInterval(foo, 3600);}
function Load_Note() {console.log("api loded")}