JavaScript Call function then call it after x seconds continuously [duplicate] - javascript

This question already has answers here:
Execute the setInterval function without delay the first time
(18 answers)
Closed 5 years ago.
Following calls a functions every 10 seconds.
It does not call the function immediately, just after the first 10 seconds.
window.setInterval(function(){
/// foo
}, 10000);
How do I call the function first, then call it every x seconds, what would be the best way of doing this?

Either give it a name and call it right after the setInterval
function repeat(){
//foo
}
window.setInterval(repeat, 10000);
repeat();
Or use setTimeout instead and call it from inside the function
function repeat(){
//foo
setTimeout(repeat, 10000);
}
repeat();

EDIT:
<html>
<head><title>Timeout testing</title></head>
<body onload="callMe()">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
function callMe()
{
window.console.log('called');
window.setTimeout(callMe, 1000);
}
$(".realContent").click(function() {
var data = [ {"id":1,"start":"/Date(1401993000000+0530)/"} ];
var myDate = new Date(data[0].start.match(/\d+/)[0] * 1);
myDate = new Date(myDate.getTime() + myDate.getTimezoneOffset() * 60 * 1000);
alert(myDate);
})
</script>
</body>
</html>

Related

How to stop this javascript count down when finished? [duplicate]

This question already has answers here:
Stop setInterval call in JavaScript
(7 answers)
Closed 3 years ago.
I found this javascript and it starts a new count down after finished in a loop
<script>
var countdownNumberEl = document.getElementById('countdown-number');
var countdown = 10;
countdownNumberEl.textContent = countdown;
setInterval(function() {
countdown = --countdown <= 0 ? 10 : countdown;
countdownNumberEl.textContent = countdown;
}, 1000);
</script>
SetInterval returns a unique ID.
var intervalId = setInterval( function(){}, 1000);
so, when you want it to stop, you will just call clearInterval(intervalId)
If you want to call it in the function itself, you need to just have the correct conditional to monitor when you want it to stop it you would need to reference the global or scoped identifier.
In your example, you are using a countdown variable.
So you can say something like:
if (countdown <= 0) clearInterval(intervalId);

javascript setInterval only work once? [duplicate]

This question already has answers here:
Why does the setInterval callback execute only once?
(2 answers)
Closed 4 years ago.
i need to show current time in html code, but the javascript code only work once?
$(document).ready(function () {
function updateClock(ele){
var current_time = new Date();
var current_time_str = current_time.toLocaleTimeString();
ele.text(current_time_str);
console.log(current_time_str);
}
setInterval(updateClock($('#clock')) , 1000 );
})
It's work different some others languages like C,Object-C or Python, it's so misleading for me.
You need to wrap the calling part in a function, because it is called only once and returns undefined as calling value.
setInterval(() => updateClock($('#clock')), 1000);
Another possibillity is to use the third and following arguments of setInterval
setInterval(updateClock, 1000, $('#clock'));
Put the updateClock inside setInterval callback function
$(document).ready(function() {
function updateClock(ele) {
var current_time = new Date();
var current_time_str = current_time.toLocaleTimeString();
ele.text(current_time_str);
}
setInterval(function() {
updateClock($('#clock'))
}, 1000);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="clock"></div>

setInterval function runs only once [duplicate]

This question already has answers here:
Why does the setInterval callback execute only once?
(2 answers)
Closed 6 years ago.
function updateCounter(){
console.log(delay);
delay = delay - 1000;
$('#counter-value').html(delay / 1000);
if(delay <= 0){
clearInterval(loopID);
}
}
var delay = 5000;
var loopID = setInterval(updateCounter(), 1000);
I don't understand why it doesn't work, could someone help me? I've looked many things but couldn't end up making it. :(
You need to pass the function name or reference--remove ()
var loopID = setInterval(updateCounter, 1000);

Loop a function without changing pages [duplicate]

This question already has answers here:
Calling a function every 60 seconds
(15 answers)
Closed 5 years ago.
JQuery, how to call a function every 5 seconds.
I'm looking for a way to automate the changing of images in a slideshow.
I'd rather not install any other 3rd party plugins if possible.
You don't need jquery for this, in plain javascript, the following will work:
var intervalId = window.setInterval(function(){
// call your function here
}, 5000);
To stop the loop you can use:
clearInterval(intervalId)
you could register an interval on the page using setInterval, ie:
setInterval(function(){
//code goes here that will be run every 5 seconds.
}, 5000);
A good example where to subscribe a setInterval(), and use a clearInterval() to stop the forever loop:
function everyTime() {
console.log('each 1 second...');
}
var myInterval = setInterval(everyTime, 1000);
call this line to stop the loop:
clearInterval(myInterval);
Just a little tip for the first answer. If your function is already defined, reference the function but don't call it!!! So don't put any parentheses after the function name. Just like:
my_function(){};
setInterval(my_function,10000);
The functions mentioned above execute no matter if it has completed in previous invocation or not, this one runs after every x seconds once the execution is complete
// IIFE
(function runForever(){
// Do something here
setTimeout(runForever, 5000)
})()
// Regular function with arguments
function someFunction(file, directory){
// Do something here
setTimeout(someFunction, 5000, file, directory)
// YES, setTimeout passes any extra args to
// function being called
}
Both setInterval and setTimeout can work for you (as #Doug Neiner and #John Boker wrote both now point to setInterval).
See here for some more explanation about both to see which suits you most and how to stop each of them.
you can use window.setInterval and time must to be define in miliseconds, in below case the function will call after every single second (1000 miliseconds)
<script>
var time = 3670;
window.setInterval(function(){
// Time calculations for days, hours, minutes and seconds
var h = Math.floor(time / 3600);
var m = Math.floor(time % 3600 / 60);
var s = Math.floor(time % 3600 % 60);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = h + "h "
+ m + "m " + s + "s ";
// If the count down is finished, write some text
if (time < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
time--;
}, 1000);
</script>

Using setTimeout for a counter creates a strange output? [duplicate]

This question already has answers here:
setTimeout with loop issue with field update
(2 answers)
Closed 8 years ago.
I checked, doubled checked and rechecked this code to make sure it works properly (and it's simple) yet I cannot figure out why I get ~count: 17k for the output, please help...
Thanks
<html>
<head>
</head>
<body onload = "counter()">
<script type="text/javascript">
var count = 0;
function counter()
{
document.getElementById("div_1").innerHTML = "count: "+count;
count++;
setTimeout(counter(), 1000);
}
</script>
<div id = "div_1"></div>
</body>
</html>
Do not call, just reference
setTimeout(counter, 1000);
you are passing the result of counter() into setTimout, instead of just setTimeout(counter, 1000). effectively, its just a recursive function. what you are doing is this:
var count = 0;
var counter = function(){
count++;
//Don't flood the console
//console.log(count);
document.querySelector("#div1").innerHTML = "count: " + count;
//you probably don't want this
counter();
//but this
//setTimeout(counter, 1000);
};
your result of 17k is where count was at when javascript exhausted its call stack
Wrap function in an anonymous function
setTimeout(function(){counter()}, 1000);
http://jsfiddle.net/tgLqH/

Categories

Resources