Why is the setTimeout only being called once?
repeatSubscriber = function(observer) {
observer.next('first');
(function() {
setTimeout(() => {
observer.next('repeating timed resp');
}, 3000);
}());
};
Prints:
first
repeating timed resp
setTimeout() is only supposed to trigger once - what you need is setInterval().
Because it should:
setTimeout() sets a timer which executes a function or specified piece of code once after the timer expires.
More at MDN
What you are looking for is setInterval()
repeatSubscriber = function(observer) {
observer.next('first');
(function() {
setInterval(() => {
observer.next('repeating timed resp');
}, 3000);
}());
};
Because it worked like this its in the function nature,
If you need repeated call you need setInterval function
Related
In the following throttle function, timeout eventually turns into a number as it's assigned to the setTimeout. I'm redefining it as false as it's cleared, the code works.
I don't notice anything on the surface, but wondering if there are any issues with doing things this way or there's something I might be missing?
const throttle = (fn, delay) => {
let timeout;
return (...args) => {
if(!timeout) {
timeout = setTimeout(() => {
fn(...args);
clearTimeout(timeout = false);
}, delay);
}
}
};
The code:
clearTimeout(timeout = false)
is evaluated as:
timeout = false;
clearTimeout(timeout)
which means you call clearTimeout(false) and this is not correct. clearTimeout() should be called with a timeout ID returned by setTimeout().
It seems it works because you call clearTimeout() from the function that executes when the timeout expires. The call to clearTimeout() does not work but the timeout already expired and JavaScript clears it anyway.
Calling clearTimeout() from the timeout callback is not needed and does not help. The purpose of clearTimeout() is to call it before the timeout expires, to prevent the execution of the callback set with setTimeout().
Your code should be:
timeout = setTimeout(() => {
fn(...args);
timeout = false;
}, delay);
I have a app that must send the user to homepage after some events. For this I use this bit of code that works good:
var waitime = 1000;
var handle=setInterval(function () {
$('.wrapper').html(divResp);
$('body').append(js);
clearInterval(handle);
}, waitime);
But I was trying to create a function to be called instead copy the code every time. So, after some reseach setInterval and how to use clearInterval and clearInterval outside of method containing setInterval I have create this one:
function refreshToHomePage3(handle,waitime){
return setInterval(function () {
$('.wrapper').html(divResp);
$('body').append(js);
clearInterval(handle);
}, waitime);
}
The problem is when a call the function, like this:
var refreshIntervalId=refreshToHomePage3(refreshIntervalId,waitime);
I have a infinite loop. I already solved the problem using setTimeout instead of setInterval and the function became like this one:
function refreshToHomePage2(waitime){
setTimeout(function () {
$('.wrapper').html(divResposta);
$('body').append(js);
}, waitime);
}
But I was wondering how to solve the problem using setInterval and clearInterval. Any thougths?
setTimeout is prefered here. But you can use setInterval like this..
function refreshToHomePage3(handle,waitime){
handle = setInterval(function () {
$('.wrapper').html(divResp);
$('body').append(js);
clearInterval(handle);
}, waitime);
return handle;
}
Actually there is no need to pass a handle variable into the function.
function refreshToHomePage3(waitime){
var handle = setInterval(function () {
alert("called after waitime");
clearInterval(handle);
}, waitime);
return handle;
}
var handle = refreshToHomePage3(5000);
You're clearing the interval after the first time the code runs. So what you're doing is just what setTimeout does. You need setTimeout which runs only once after the waiting for waitTime.
function refreshToHomePage(handle, waitime) {
setTimeout(function() {
$('.wrapper').html(divResp);
$('body').append(js);
clearInterval(handle);
}, waitime);
}
If you want your code to be executed just once after the wait time, setInterval is not the right function for this job, but setTimeout is.
setInterval will execute your code every n seconds until you execute clearInterval. However, setTimeout will execute your code once after n seconds and is therefore the correct approach for your problem.
Don't try to make setInterval something that it isn't :)
In JavaScript, How can I call a function after a specific time interval?
Here is my function I want to run:
function FetchData() {
}
You can use JavaScript Timing Events to call function after certain interval of time:
This shows the alert box every 3 seconds:
setInterval(function(){alert("Hello")},3000);
You can use two method of time event in javascript.i.e.
setInterval(): executes a function, over and over again, at
specified time intervals
setTimeout() : executes a function, once, after waiting a
specified number of milliseconds
Execute function FetchData() once after 1000 milliseconds:
setTimeout( function() { FetchData(); }, 1000);
Execute function FetchData() repeatedly every 1000 milliseconds:
setInterval( FetchData, 1000);
ECMAScript 6 introduced arrow functions so now the setTimeout() or setInterval() don't have to look like this:
setTimeout(function() { FetchData(); }, 1000)
Instead, you can use annonymous arrow function which looks cleaner, and less confusing:
setTimeout(() => {FetchData();}, 1000)
sounds like you're looking for setInterval. It's as easy as this:
function FetchData() {
// do something
}
setInterval(FetchData, 60000);
if you only want to call something once, theres setTimeout.
Timeout:
setTimeout(() => {
console.log('Hello Timeout!')
}, 3000);
Interval:
setInterval(() => {
console.log('Hello Interval!')
}, 2000);
setTimeout(func, 5000);
-- it will call the function named func() after the time specified.
here, 5000 milli seconds , i.e) after 5 seconds
I am trying to use the jQuery setTimeout in order to call a method each x time interval:
$('.text').blur(function () {
doSmth();
});
$('.text').bind("paste", function (e) {
setTimeout(function () {
doSmth();
}, 5);
});
The timeout is not working , please advice !
What do you mean with "it's not working"?Anyway setTimeout() is a Javascript function that triggers only once after the specified interval.
If you wan't to trigger something every five second you should do:
var interval = setInterval(doSmth, 5000);
Where doSmth is a function defined elsewhere and 5000 is the number of millisecond of the interval. If yo want to stop the execution just do:
clearInterval(interval);
First, it isn't a "jQuery setTimeout". setTimeout is part of the native API, not jQuery's API.
Second, I assume you want 5 seconds. Currently you're doing 5 milliseconds.
$('.text').bind("paste", function(e) {
setTimeout(function() {
doSmth();
}, 5000);
});
The duration of 5 in your code is far too short to be perceptible.
I see that the other answers user setInterval, but from what I've read, you should avoid using setInterval, since you can end up with a stack of not-yet-executed function calls etc.
So what you could do instead is something like this:
var myTimeout;
$('.text').bind("paste", function (e) {
function loopFunction () {
doSmth();
myTimeout = setTimeout(loopFunction, 5000);
}
myTimeout = setTimeout(loopFunction, 5000);
});
Now you have a function that calls itself every five seconds.
According to your feedback,here is the solution:
var interval = setInterval(doSmth, 5000);
$('.text').blur(function() {
doSmth();
});
$('.text').bind("paste", function(e) {
setTimeout(function() {
doSmth();
}, 0);
});
Thanks for you amazing support.
I want to be able to call the function work() every 6 seconds. My jQuery code is
function looper(){
// do something
if (loopcheck) {
setInterval(work,6000);
}
else {
console.log('looper stopped');
}
}
The problem I am running into is that it loops over work twice quickly, and then it will wait for 6 seconds. i tried using setTimeout with similar results.
What could be causing work to be called twice before the delay works?
setInterval should be avoided. If you want work to be repeatedly called every 6 seconds, consider a recursive call to setTimeout instead
function loopWork(){
setTimeout(function () {
work();
loopWork();
}, 6000);
}
Then
function looper(){
// do something
if (loopcheck) {
loopWork()
}
else {
console.log('looper stopped');
}
}
And of course if you ever want to stop this, you'd save the value of the last call to setTimeout, and pass that to clearTimeout
var timeoutId;
timeoutId = setTimeout(function () {
work();
loopWork();
}, 6000);
Then to stop it
clearTimeout(timeoutId);
Use old-style setTimeout()
var i=0;
function work(){
console.log(i++);
}
function runner(){
work();
setTimeout(runner, 6000);
}
runner();
I prefer the following pattern myself I find it easier to follow:
function LoopingFunction() {
// do the work
setTimeout(arguments.callee, 6000); // call myself again in 6 seconds
}
And if you want to be able to stop it at any point:
var LoopingFunctionKeepGoing = true;
function LoopingFunction() {
if(!LoopingFunctionKeepGoing) return;
// do the work
setTimeout(arguments.callee, 6000); // call myself again in 6 seconds
}
Now you can stop it at any time by setting LoopingFunctionKeepGoing to false.