This question already has answers here:
What's the easiest way to call a function every 5 seconds in jQuery? [duplicate]
(7 answers)
Closed 8 years ago.
How do I get this javascript to run every second?
source code:
<script type="text/javascript">
$(function() {
//More Button
$('.more').live("click",function() {
var ID = $(this).attr("id");
if(ID) {
$("#more"+ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "ajax_more.php",
data: "lastmsg="+ ID,
cache: false,
success: function(html){
$("ol#updates").prepend(html);
$("#more"+ID).remove();
}
});
} else {
$(".morebox").html('no posts to display');
}
return false;
});
});
</script>
Use setInterval() to run a piece of code every x milliseconds.
You can wrap the code you want to run every second in a function called runFunction.
So it would be:
var t=setInterval(runFunction,1000);
And to stop it, you can run:
clearInterval(t);
Use setInterval:
$(function(){
setInterval(oneSecondFunction, 1000);
});
function oneSecondFunction() {
// stuff you want to do every second
}
Here's an article on the difference between setTimeout and setInterval. Both will provide the functionality you need, they just require different implementations.
You can use setTimeout to run the function/command once or setInterval to run the function/command at specified intervals.
var a = setTimeout("alert('run just one time')",500);
var b = setInterval("alert('run each 3 seconds')",3000);
//To abort the interval you can use this:
clearInterval(b);
window.setTimeout(func,1000);
This will run func after 1000 milliseconds. So at the end of func you can call window.setTimeout again to go in a loop of 1 sec. You just need to define a terminate condition.
Reference
You can use setInterval:
var timer = setInterval( myFunction, 1000);
Just declare your function as myFunction or some other name, and then don't bind it to $('.more')'s live event.
Use setInterval(func, delay) to run the func every delay milliseconds.
setTimeout() runs your function once after delay milliseconds -- it does not run it repeatedly. A common strategy is to run your code with setTimeout and call setTimeout again at the end of your code.
Related
I am trying to call a function every few seconds as shown here:
HTML:
<div id="Result">Click here for the message.</div>
JS:
$(document).ready(function () {
$("#Result").click(function () {
var timeout = setTimeout(function () {
$('post').each(function () {
dater();
});
}, 3000);
});
});
function dater() {
$("#Result").text("hi");
}
The problem is that this is not being triggered; so, what am I missing, or doing wrong?
Alternatively, is there a better way to do what I am trying to do?
Problem #1
You did not include jQuery in the JS Fiddle demo.
Problem #2
A setTimeout only executes once, unless it calls itself. Either do that or use setInterval, which executes every x milliseconds.
Also, there are no <post> elements in HTML, use a class instead. Also include it in the fiddle or it won't work.
$(document).ready(function () {
$("#Result").click(function () {
var timeout = setInterval(function () {
$('.post').each(dater);
}, 3000);
});
});
function dater() {
$("#Result").text("hi");
}
JS Fiddle Demo
Note
Both setTimeout and setInterval only start after the time set. If you want the function to be executed instantly as well, you could do something like this.
Let's go further
It might be a better choice to use setTimeout, as mentioned in other answers. Here is an example on how to do that:
var timeout;
$(document).ready(function () {
$("#Result").click(daterForEachPost);
});
function daterForEachPost() {
$('.post').each(dater);
// The function will call itself every 3000 ms
timeout = setTimeout(daterForEachPost, 3000);
}
function dater() {
$("#Result").text("hi");
}
JS Fiddle Demo
The .setTimeout() method will run only once. In order to run periodically (with the specified timeout interval), use .setInterval().
Try to use setInterval() instead.
Here the information provided in w3schools.
"The setInterval() method will wait a specified number of milliseconds, and then execute a specified function, and it will continue to execute the function, once at every given time-interval."
This question already has answers here:
how to kill a setTimeout() function
(5 answers)
Stop scheduled JavaScript execution
(4 answers)
Closed 9 years ago.
The title may be misleading, but it's essentially what I need to accomplish.
I have an AJAX "Loading" text that I want to update if the server has taken more than 15 seconds to respond.
Here is the code:
$(".loader").html('Loading');
$(".loader").show();
setTimeout(function () {
if ($('.loader').is(":visible")) {
$(".loader").html('Click here to reload.</span>');
}
}, 15000);
Is there a better approach? When I eventually call $(".loader").hide(); I want the setTimeout counter to be aborted. Is it possible?
Sure. setTimeout returns a value you can pass to clearTimeout in order to stop timeout.
var handle = setTimeout(function () {
alert("Oh noes, I ran!")
}, 5000)
clearTimeout(handle)
You can use the clearTimeout function:
$(".loader").html('Loading');
$(".loader").show();
var timerId= setTimeout(function () {
if ($('.loader').is(":visible")) {
$(".loader").html('Click here to reload.</span>');
}
}, 15000);
$(".stop").click(function () {
clearTimeout(timerId);
$(".loader").html("done");
});
See this fiddle: http://jsfiddle.net/KaNUP/
I would recommend to make a shorter period (1 sec) and increment counter inside function you call. Then you can exit on successfull load or counter threshold, whichever comes earlier.
This question already has answers here:
Why is my function call that should be scheduled by setTimeout executed immediately? [duplicate]
(3 answers)
Closed 7 years ago.
I wanted a JavaScript function to run 60 seconds after page is loaded.
After a little research I have made, I've found that setTimeout() is the solution.
So that's what I did:
<body onLoad="setTimeout(postAction('news.reads', 'article'), 60000);">
Somehow, setTimeout does not work. After the page is loaded, there's no need to wait 60 seconds because postAction() runs immediately.
Why is it happening? How to solve it? Are there alternatives to setTimeout() up there?
Thank you!
You need to wrap postAction in a function to defer execution:
setTimeout(function() { postAction('news.reads', 'article'); }, 60000);
You are actually executing postAction immediately, your code is equivalent to:
var result = postAction('news.reads', 'article');
setTimeout(result, 60000);
The correct way to do what you want in JS, ie setting a timeout after the page is loaded:
(function(w)
{
var load = function()
{
setTimeout(postAction,60000);
if (w.removeEventListener)
{//remove listeners, to avoid leak...
return w.removeEventListener('load',load,false);
}
return w.attachEvent('onload',load);
};
if (w.addEventListener)
{
return w.addEventListener('load',load,false);
}
return w.attachEvent('onload',load);
}(this));
Instead of window.onload = function(){setTimeout(postAction,60000);};, which will work, too, but cause a mem-leak in IE <9. That's just for completeness' sake
Anyway, the key line here is setTimeout(postAction,60000);
Update
After seeing the code you're using, this is the easiest fix:
<body onLoad="setTimeout(function(){ return postAction('news.reads', 'article');}, 60000);">
Are you using setTimeout like :
setTimeout(function(){alert("OK");}, 1000 * 60); // alert "OK" in 60s
<script>
function doSomeJavascript() {
// javascript code goes here
alert('5 secs is up!');
}
// calls function doSomeJavascript() 5 secs after page load
var interval = setInterval(doSomeJavascript, 5000);
setTimeout(function() {
window.clearInterval(interval);
}, 5000);
</script>
How can I run a Javascript function with per-set time delays, without using any framework?
I have a Ajax script which will fetch the no of online users from server. This script i want to run in a regular timed delays.
Thanks in advance.
The simplest way would be with setInterval:
setInterval(function() {
console.log("run every second");
}, 1000);
This will run the given code at the specified time interval over and over.
var interval = window.setInterval(function() {
console.log("foo");
}, 1000);
And stop
window.clearInterval(interval);
You can use setInterval to do this.
See: https://developer.mozilla.org/en/DOM/window.setInterval
var int = self.setInterval(askQuestion,1000);
function askQuestion() {
// do something... code to be implemented.
}
Will be call askQuestion() every 1000 milliseconds (1 seconds) for example..
<script>
var intervalVariable=setInterval(function(){
//Your operation goes Here
},1000); // executes every 1000 milliseconds(i.e 1 sec)
function stopTimer()
{
clearInterval(intervalVariable); // To clear TimerInterval/stop the setInterval Function
}
</script>
I've done this a month before...
But now its not working...
The code is
window.onload = function(){
setTimeout(function(){
alert("Hello");
}, 10000);
};
This is written in script in head of the test.php page.
The script and other tags are correct.
I would like to call a specific function every 10 seconds. The alert just shows once only. This is problem in every browser....
After this testing i would like to check the url every 2 seconds and call an AJAX function.
Any Help??
That's what setTimeout does (executes once after a specified interval). You're looking for setInterval (calls a function repeatedly, with a fixed time delay between each call to that function):
window.onload = function(){
setInterval(function(){
alert("Hello");
}, 10000);
};
Use setInterval instead.
var fn = function(){alert("Hello")};
It is possible using setTimeout:
window.onload = function(){ setTimeout( function(){ fn();window.onload() },10000) };
but the best solution is setInterval:
window.onload = function() { setInterval(fn,10000)};
setTimeout is intended for one-time run. Look at setInterval function.