It's there a way to configure the setInterval method of javascript to execute the method immediately and then executes with the timer
问题:
回答1:
It's simplest to just call the function yourself directly the first time:
foo(); setInterval(foo, delay); However there are good reasons to avoid setInterval - in particular in some circumstances a whole load of setInterval events can arrive immediately after each other without any delay. Another reason is that if you want to stop the loop you have to explicitly call clearInterval which means you have to remember the handle returned from the original setInterval call.
So an alternative method is to have foo trigger itself for subsequent calls using setTimeout instead:
function foo() { // do stuff // ... // and schedule a repeat setTimeout(foo, delay); } // start the cycle foo(); This guarantees that there is at least an interval of delay between calls. It also makes it easier to cancel the loop if required - you just don't call setTimeout when your loop termination condition is reached.
Better yet, you can wrap that all up in an immediately invoked function expression which creates the function, which then calls itself again as above, and automatically starts the loop:
(function foo() { ... setTimeout(foo, delay); })(); which defines the function and starts the cycle all in one go.
回答2:
I'm not sure if I'm understanding you correctly, but you could easily do something like this:
setInterval(function hello() { console.log('world'); return hello; }(), 5000); There's obviously any number of ways of doing this, but that's the most concise way I can think of.
回答3:
Here's a wrapper to pretty-fy it if you need it:
(function() { var originalSetInterval = window.setInterval; window.setInterval = function(fn, delay, runImmediately) { if(runImmediately) fn(); originalSetInterval(fn, delay); }; })(); Set the third argument of setInterval to true and it'll run for the first time immediately after calling setInterval:
setInterval(function() { console.log("hello world"); }, 5000, true); Or omit the third argument and it will retain its original behaviour:
setInterval(function() { console.log("hello world"); }, 5000); Some browsers support additional arguments for setInterval which this wrapper doesn't take into account; I think these are rarely used, but keep that in mind if you do need them.
回答4:
You could wrap setInterval() in a function that provides that behavior:
function instantGratification( fn, delay ) { fn(); setInterval( fn, delay ); } ...then use it like this:
instantGratification( function() { console.log( 'invoked' ); }, 3000); 回答5:
I stumbled upon this question due to the same problem but none of the answers helps if you need to behave exactly like setInterval() but with the only difference that the function is called immediately at the beginning.
Here is my solution to this problem:
function setIntervalImmediately(func, interval) { func(); return setInterval(func, interval); } The advantage of this solution:
- existing code using
setIntervalcan easily be adapted by substitution - works in strict mode
- it works with existing named functions and closures
- you can still use the return value and pass it to
clearInterval()later
Example:
// create 1 second interval with immediate execution var myInterval = setIntervalImmediately( _ => { console.log('hello'); }, 1000); // clear interval after 4.5 seconds setTimeout( _ => { clearInterval(myInterval); }, 4500); To be cheeky, if you really need to use setInterval then you could also replace the original setInterval. Hence, no change of code required when adding this before your existing code:
var setIntervalOrig = setInterval; setInterval = function(func, interval) { func(); return setIntervalOrig(func, interval); } Still, all advantages as listed above apply here but no substitution is necessary.
回答6:
If you extract the code you are passing to setInterval into a function, you can call the function directly immediately after calling setInterval. This achieves the same effect.
回答7:
// YCombinator function anonymous(fnc) { return function() { fnc.apply(fnc, arguments); return fnc; } } // Invoking the first time: setInterval(anonymous(function() { console.log("bar"); })(), 4000); // Not invoking the first time: setInterval(anonymous(function() { console.log("foo"); }), 4000); // Or simple: setInterval(function() { console.log("baz"); }, 4000); 回答8:
I will suggest calling the functions in the following sequence
var _timer = setInterval(foo, delay, params); foo(params) You can also pass the _timer to the foo, if you want to clearInterval(_timer) on a certain condition
var _timer = setInterval(function() { foo(_timer, params) }, delay); foo(_timer, params); 回答9:
To solve this problem , I run the function a first time after the page has loaded.
function foo(){ ... } window.onload = function() { foo(); }; window.setInterval(function() { foo(); }, 5000); 回答10:
Use:
function poll(f, i){ var cancel = false; function again(){ f(); cancel || setTimeout(again, i); } again(); return function(){ cancel = true; } } poll(task, 1000); With UI effects, compose anim into the poll to further reduce processing overhead:
function anim(f){ var waf = window.requestAnimationFrame; //browser support? return waf ? function(){ waf(f) } : f; } poll(anim(taskUI), 1000); 回答11:
There's a problem with immediate asynchronous call of your function, because standard setTimeout/setInterval has a minimal timeout about several milliseconds even if you directly set it to 0. It caused by a browser specific work.
An example of code with a REAL zero delay wich works in Chrome, Safari, Opera
function setZeroTimeout(callback) { var channel = new MessageChannel(); channel.port1.onmessage = callback; channel.port2.postMessage(''); } You can find more information here
And after the first manual call you can create an interval with your function.
回答12:
actually the quickest is to do
interval = setInterval(myFunction(),45000) this will call myfunction, and then will do it agaian every 45 seconds which is different than doing
interval = setInterval(myfunction, 45000) which won't call it, but schedule it only