Hey i am creating a DOM javascript library and i found myself having the following problem:
For example, if i take a function lets say function update() how can i check if this function has been created on another file; If it has been created on another file how can I make it run once or every couple of seconds without the user need to do this?
For example in the library p5.js :
//If this function has created on this file it will run every one second
function update(){
}
&&
//if this function has created on this file it will call itself once the page is loaded
function start(){
}
*Edit: tried to be more clear on my question thank you for your answers!
Instead of the user needing to call setInterval() to repeat update(), it can call it itself.
function update() {
setInterval(function() {
// do something
}, 1000);
}
All the actual work that needs to be done goes where // do something is.
setTimeout(func, 1000) will call func 1000 milliseconds later.
If you wanted your function to call immediately, you could do a recursion (bad way, better use a loop, but it's useful to illustrate the next example):
// calls itself infinitely, without any delay
function update(){
update(); // Will cause a stack overflow, infinitely deep recursion
}
Now you can make use of setTimeout and tell update to run a second later.
// calls itself infinitely, 1 second delay between calls
function update(){
setTimeout(update, 1000);
}
There is no recursion here. Instead, you defer the call to update() for one second. The second time update() is called, another setTimeout will be called, and so on infinitely.
The second part of your question:
//call itself once the page is loaded
function start(){
}
You can set an event listener to when the page is loaded, and call that function:
window.addEventListener('load', start);
Do this right after defining start().
To reflect your comment:
If you want to detect if the global function update has been defined (by the user, probably) and want to start calling it automatically on equal intervals of 1 second, you'll need to check its existance with typeof and then apply setInterval on it:
if(typeof update === "function") {
setInterval(update, 1000);
}
To make it explicit that you're refering to a global update and not a local variable, you can use window.update instead. In that case, you could also check if it exists this way:
if(update in window)
Related
I am making a Snake game on my webpage using JavaScript and HTML. In this game I want to call a function after regular time intervals. This function will update and print the position of the snake.
For this I am using setTimeOut(my_function,time).
My code looks like this
function my_function(){
// update values
// display snake
setTimeOut(my_function,time)
}
My question is - Will the above code create a lot of function calls on the function stack like a recursive function. I think it will.
Below is how I think I can optimise it.
function empty_function{
}
while(true){
//update values
//display snake
setTimeOut(empty_function,time)
}
Will this method will also create a lot of function calls on the function stack like a recursive function?
Your optimized solution is actually the one that will crash the program, because it keeps the same function running forever. Your first approach is perfectly fine: setTimeout doesn't call the function immediately but schedules it to be run. In the meantime your process can handle other events and start with a new stack when your function is due to be called.
In your infinite while loop your function will never even be called, as there will never be time for the program to check its scheduled task list.
If your interval is frame based (for example, you wish to update your graphics as often as possible) you might be better off with requestAnimationFrame():
function update(timestamp) {
// render your game
// request this function to be run again on the next frame:
window.requestAnimationFrame(update);
}
window.requestAnimationFrame(update);
As you can see it uses the same approach, but is specifically designed to try and match the refresh rate of the users screen freeing you from having to define the interval between render ticks.
You can achieve this more easily by setInterval.Here is an example;
setTimeout(() => {console.log('this will get printed only once after 1000 ms')}, 1000);
setInterval(() => {console.log('this will get printed after every 1000 ms')}, 1000);
setInterval runs a function again and again after given interval of time.
If you want to stop the setInterval function, this is how you can do it;
let myinterval = setInterval(() => {console.log('Print this again and again after 1000 ms')}, 1000);
// Down here i am clearing the 'myInterval' interval using the 'clearInterval' function.
const clear = () => {
console.log('printing stopped');
clearInterval(myinterval);
}
document.getElementById('stop').addEventListener('click', clear);
<button id='stop'>Stop printing</button>
I want to call a function in JavaScript continuously, for example each 5 seconds until a cancel event.
I tried to use setTimeout and call it in my function
function init()
{ setTimeout(init, 5000);
// do sthg
}
my problem is that the calls stops after like 2 min and my program is a little bit longer like 5 min.
How can i keep calling my function as long as i want to.
thanks in advance
The only conceivable explanations of the behavior you describe are that:
As another poster mentioned, init is somehow getting overwritten in the course of executing itself, in the // do sthg portion of your code
The page is being reloaded.
The //do sthg code is going into some kind of error state which makes it looks as if it not executing.
To guarantee that init is not modified, try passing the // do sthg part as a function which we will call callback:
function startLoop(callback, ms) {
(function loop() {
if (cancel) return;
setTimeout(loop, ms);
callback();
}());
}
Other posters have suggested using setInterval. That's fine, but there's
nothing fundamentally wrong with setting up repeating actions using setTimeout with the function itself issuing the next setTimeout as you are doing. it's a common, well-accepted alternative to setting up repeating actions. Among other advantages, it permits the subsequent timeouts to be tuned in terms of their behavior, especially the timeout interval, if that's an issue. If the code were to be rewritten using requestAnimationFrame, as it probably should be, then there is no alternative but to issue the next request within the callback, because requestAnimationFrame has no setInterval analog.
That function is called setInterval.
var interval = setInterval(init, 5000);
// to cancel
clearInterval(interval);
I have created a JavaScript function that does the following:
function myFunction() {
DoStuff;
watch = setTimeout(myFunction, 1000);
}
where
watch
is a global variable initially set to null.
Then, I have a second function, that can be called at any moment, of the form:
function mySecond() {
DoStuff;
clearTimeout(watch);
}
Now, it happens sometimes that, although the second function is called and the timeout is somehow cleared, the first function is called another time. I guess this is happening because when the second function is called, a request for the first function has already been sent, and thus the timer works another time, and keeps calling itself over and over... I would like to point out that this does not happen always, I guess it depends on a specific timing condition you can encounter.
How to safely remove ALL the possibilities that the first function is called again?
Problem with this code is watch holds the last timeout only. This should fix it
function myFunction() {
DoStuff;
if (watch) { clearTimeout(watch); }
watch = setTimeout(myFunction, 1000);
}
I have created a JavaScript version of the Little Man Computer based on the Java one at http://www.atkinson.yorku.ca/~sychen/research/LMC/LMCHome.html
I have it working in by stepping through each instruction. I have a function called stepCode() that does this.
What I want is a function that will run the program, pausing for a second between each step until the simulated program ends.
The code I have is this:
function runProgram()
{
var milliseconds = 1000;
var timeOut;
programRunning = true;
while(programRunning)
{
timeOut = setTimeOut(stepCode(), milliseconds);
}
}
This seems does not work. It still performs all the stepCode() calls one after the other very quickly. I want to pause between each stepCode() call.
I'm obviously doing something wrong. Any ideas?
You should use setInterval instead of setTimeout. Additionally, you need to reference the function, not call the function:
var timeOut; // global timeout variable to ensure both methods have access to it.
function runProgram() {
var milliseconds = 1000;
timeOut = setInterval(stepCode, milliseconds); // use setInterval instead of setTimeout
}
function stepCode {
// ... code processing here ...
// I assume you are setting programRunning to false at some point in this method.
// Instead of setting programRunning = false, you would do:
clearInterval(timeOut);
// Note, if you only have one timeout interval set, you can use clearInterval();
}
setInterval will cause the stepCode function to run every 'milliseconds' until you call clearInterval(timeOut);; setTimeout will only queue it up once. Anything that is queued via setTimeout will not execute until the current flow of code has been completed. As a result, programRunning will run and queue up several setTimeout executions. Once the programRunning variable hit false, the current code flow will finish and ALL of the queues will wait 1 second, and effectively execute all at the same time, or in rapid succession.
When you pass in a method call (e.g. stepCode()), it will call the method. You have to pass a reference to the function stepCode (notice no parens), to ensure that it knows what to run each time it executes.
This Fiddle Demo simulates a counter, which is common thing people attempt to execute using setInterval. It demonstrates the basic concept and use of setInterval.
In addition to suggested setInterval use that will call stepCode at 1 second intervals until cleared (or until the page is reloaded), and correction of removing () after stepCode that results in immediate stepCode executon, you can still use setTimeout if they are chained as shown below. Depending on what stepCode does and how long it takes, this solution has an advantage of ensuring that there is 1 second of idle time between the end of the previous and the beginning of the next stepCodes.
var milliseconds = 1000;
function runProgram()
{
programRunning = true;
stepCodeWrapper();
}
function stepCodeWrapper() {
if (programRunning) {
stepCode();
setTimeOut(stepCodeWrapper, milliseconds);
}
}
Just try with:
timeOut = setInterval(stepCode, milliseconds);
Bic, thanks for your swift response. You are correct about the programRunning flag being set to false inside the stepCode() function. I've set it as a global variable so that I could possibly halt the program by pressing a button, but thats another problem.
Tried both setInterval and setTimeout. You are right about it repeatedly calling the function. Using either method locks up the browser with repeated function calls. This is probably as its in a while loop. I cannot think of another was to repeatedly call the stepCode() function otherwise.
I sort of understand the difference between setInterval & setTimeout. Thanks, and I understand that would make the while loop redundant, but then how to stop it calling the stepCode function when the programRunning flag is set to false?
Is there any way to call a function periodically in JavaScript?
The setInterval() method, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. It returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval().
var intervalId = setInterval(function() {
alert("Interval reached every 5s")
}, 5000);
// You can clear a periodic function by uncommenting:
// clearInterval(intervalId);
See more # setInterval() # MDN Web Docs
Please note that setInterval() is often not the best solution for periodic execution - It really depends on what javascript you're actually calling periodically.
eg. If you use setInterval() with a period of 1000ms and in the periodic function you make an ajax call that occasionally takes 2 seconds to return you will be making another ajax call before the first response gets back. This is usually undesirable.
Many libraries have periodic methods that protect against the pitfalls of using setInterval naively such as the Prototype example given by Nelson.
To achieve more robust periodic execution with a function that has a jQuery ajax call in it, consider something like this:
function myPeriodicMethod() {
$.ajax({
url: ...,
success: function(data) {
...
},
complete: function() {
// schedule the next request *only* when the current one is complete:
setTimeout(myPeriodicMethod, 1000);
}
});
}
// schedule the first invocation:
setTimeout(myPeriodicMethod, 1000);
Another approach is to use setTimeout but track elapsed time in a variable and then set the timeout delay on each invocation dynamically to execute a function as close to the desired interval as possible but never faster than you can get responses back.
Everyone has a setTimeout/setInterval solution already. I think that it is important to note that you can pass functions to setInterval, not just strings. Its actually probably a little "safer" to pass real functions instead of strings that will be "evaled" to those functions.
// example 1
function test() {
alert('called');
}
var interval = setInterval(test, 10000);
Or:
// example 2
var counter = 0;
var interval = setInterval(function() { alert("#"+counter++); }, 5000);
Old question but..
I also needed a periodical task runner and wrote TaskTimer. This is also useful when you need to run multiple tasks on different intervals.
// Timer with 1000ms (1 second) base interval resolution.
const timer = new TaskTimer(1000);
// Add task(s) based on tick intervals.
timer.add({
id: 'job1', // unique id of the task
tickInterval: 5, // run every 5 ticks (5 x interval = 5000 ms)
totalRuns: 10, // run 10 times only. (set to 0 for unlimited times)
callback(task) {
// code to be executed on each run
console.log(task.id + ' task has run ' + task.currentRuns + ' times.');
}
});
// Start the timer
timer.start();
TaskTimer works both in browser and Node. See documentation for all features.
You will want to have a look at setInterval() and setTimeout().
Here is a decent tutorial article.
yes - take a look at setInterval and setTimeout for executing code at certain times. setInterval would be the one to use to execute code periodically.
See a demo and answer here for usage
Since you want the function to be executed periodically, use setInterval
function test() {
alert('called!');
}
var id = setInterval('test();', 10000); //call test every 10 seconds.
function stop() { // call this to stop your interval.
clearInterval(id);
}
The native way is indeed setInterval()/clearInterval(), but if you are already using the Prototype library you can take advantage of PeriodicalExecutor:
new PeriodicalUpdator(myEvent, seconds);
This prevents overlapping calls. From http://www.prototypejs.org/api/periodicalExecuter:
"it shields you against multiple parallel executions of the callback function, should it take longer than the given interval to execute (it maintains an internal “running” flag, which is shielded against exceptions in the callback function). This is especially useful if you use one to interact with the user at given intervals (e.g. use a prompt or confirm call): this will avoid multiple message boxes all waiting to be actioned."