How can you execute a command for X seconds? - javascript

I've been trying to create an object which moves up and, after three seconds, comes back down, but I can only find code which tracks how long it takes until the command executes (ex. setInterval), rather than how long the code actually runs. Does anyone know how you'd bring the object back down after a specified time interval?
addEventListener("keyup", () => {
char.style.transition = "0.3s ease";
char.style.transform = "translateY(50%)";
});

setTimeout(function(){
alert("bring down object");
//function that brings out object goes here
}, 3000);
3000 is the amount of time to wait before running the function its default is in milliseconds so here it waits for 3 seconds before running the function manipulate that number to fit your required wait time before running the function that brings back the object.

Related

How do I replace the console message without it disappearing so fast?

I tried to make a stopwatch in the console, but the message kept on clearing before I had time to read it.
I tried increasing how long the Timeout function would go, but for some reason, it didn't make a difference.
Can somebody help me with making the messages not clear so fast?
setTimeout(function() {
console.log("1");
}, 1000);
setTimeout(function() {
console.clear()
},1099);
setTimeout(function() {
console.log("2");
}, 2000);
setTimeout(function() {
console.clear()
}, 2099);
setTimeout(function() {
console.log("3");
}, 3000);
setTimeout(function() {
console.clear()
}, 3099);
second argument to settimeout represents time in milliseconds. 1000ms = 1seconds. consider this. Maybe you should increase the time it takes to run the console.clear(), base on your code it executes after 2 and 3 seconds.
#Mr.Buscuit, consider using the setInveral function,
let sec = 0;
setInterval(function () {
console.clear();
console.log(sec);
sec++;
}, 1000);
This log a new number to the log every second. Hope this helps.
1- first line of code you tell your browser to execute that function which print on console number "1"
2- second line you tell browser after 99ms (from beginning of timer) NOT 1099ms clear the console
Why 99ms? because All Timer API(Browser API) e.g (setTimeout, setInterval) works at same time, all of these functions that you do, they have a one(only one) timer, hence that means when timer reach at 1000ms, second setTimeout that you determined its timer with 1099ms reached at 1000ms as well (one timer), hence still 99ms remaining from 1099ms
Summary
Imagine there is one big timer is running for all functions, this means if we have 2 setTimeout with time we specified 1000ms (2 function with same time) this is not means after finish first function that need 1000ms, second starts setTimeout timer that will begin from scratch, hence need 1000ms again with total latency 2000ms, No, this is wrong, two functions will work together
very good resource for understand this concept : Async Concept

Does setTimeOut(function,time) keeps creating load on function stack?

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>

understanding an automatic page refresh in javascript

I am trying to understand this code:
function setIdle(cb, seconds) {
var timer;
var interval = seconds * 1000;
function refresh() {
clearInterval(timer);
timer = setTimeout(cb, interval);
};
$(document).on('keypress, click', refresh);
refresh();
}
setIdle(function() {
location.href = location.href;
}, 5);
setIdle takes two arguments. Inside its function it has a function refresh that clears a timer on a Timeout function. Now every time when an event happens (click, keypress) refresh() gets called.
and then finally this function gets called passing in another function and and int value (5) which later will be the amount of seconds for the timer. In that other function which later is represented through cb the page will be refreshed (location.href = location.href;).
This causes an automaticpage refresh every 5 seconds.
So now I don't understand if I put an additional function:
setIdle(function() {
console.log('hi');
}, 1);
Why is the second function only called once and not every second like the other one?
setIdle doesn't run the callback function every 5 seconds. It runs it once, 5 seconds after you call setIdle, and if you type or click something the timeout gets pushed back again. So it runs it once, when you've been idle for 5 seconds.
The reason the page refreshes every 5 seconds is because the callback function reloads the page, and reloading the page runs all the Javascript in the page again, so that calls setIdle() again.
But your second use of setIdle doesn't reload the page, so it just logs hi once.
If you want to do something repeatedly every N seconds, use setInterval rather than setTimeout.
BTW, clearInterval should be clearTimeout. In most browser they're currently interchangeable, but there's no guarantee. See Are clearTimeout and clearInterval the same?

Run javascript after a specify waiting time

I have a list of javascript code like below
javascript: alert("hi1");
javascript: alert("hi2");
javascript: alert("hi3");
javascript: alert("hi4");
...
javascript: alert("hi100")
I want to run 1st line, then wait for a specific time. Then run 2nd line and wait for a specific time. And run 3rd line ...till the end.
Anyone help me?
Thanks!!!
JavaScript is single-threaded and event based. It has an event loop that calls your code, and then nothing else runs until your code returns.
That means that you don't get to "wait" between two statements, because it would still block any other code from running while you wait. Instead you have to schedule a new event at a later time that executes the rest of the code, as a separate function, and then return to the event loop.
Actually, the alert function does block everything until you dismiss the alert, which is one of the reasons it should only be used for really serious problems.
Scheduling something after a specific time is done using the setTimeout function.
Try this to emulate your example:
var counter = 0;
function loop() {
counter += 1;
alert("hi" + counter);
if (counter < 100) {
setTimeout(loop, 1000); // Wait one second (1000 ms), then run again.
}
}
loop();
Here I assumed the time between alerts is always the same (1 second). If it's a simple formula depending on the counter, the example should be easy to modify.
You can also use setInterval to start a repeating timer that fires a timer event at a fixed interval. In this case, I didn't use this because the alert call actually does make everything wait, and we want the timer to only start when the alert is dismissed.
As a side note, there is no need for the "javascript:" in front of your lines. Most likely, you should never have to write "javascript:" anywhere.
Use javascript's setTimeout(function(), time_in_millis);
setTimeout(function(){alert("Hello")}, 3000);
Should do the trick.
You can use:
setTimeout(function(){alert("hi2");}, 3000);
It executes after 3000 milliseconds (waiting time).
split your alerts into functions and use setTimeout before calling the next alert
function partA() {
//line of code you want to execute
window.setTimeout(partB,1000) //wait for a sec
}
function partB() {
//line of code you want to execute
window.setTimeout(partC,1000) //wait for a sec
}
function partC() {
...
}
//repeat
Simply write time-consuming function and use it when you want to pause your script.
function pauseScript(seconds) {
var stop = Date.now() + seconds*1000;
for (var i; stop >= Date.now(); i++){}
}
So your code will look like this
alert("hi1");
pauseScript(10); # wait 10 seconds
alert("hi2");
pauseScript(7); # wait 7 seconds
alert("hi3");
pauseScript(8); # wait 8 seconds
alert("hi4");
// etc...

Trigger a function only once inside a continously triggered function

I have a function which is triggered on every mouse-down event when the mouse pointer is over the image.
Now, I call two functions in this mouse-down function.
I need one function Triangulate() be called every time and the other one ImageCalculation() last time only.
Here last time only means, a gap of minimum 3 seconds or more should be there between consecutive img_mouse_down() function calls.
Below is my code:
function img_mouse_down(){
if(leftMouseButton){
Triangulate(); //Call this function every time.
ImageCalculation(); //Call this function only the last time
}
}
If I click over the image 5 times continuously and then pauses for 3 or more seconds, Triangulate() should be called 5 times and the ImageCalculation() should be called only once.
How to achieve this?
var glob_timeout_holder;
function img_mouse_down(){
if(leftMouseButton){
Triangulate(); //Call this function every time.
clearTimeout(glob_timeout_holder); //clear if any previous continuing timeouts
glob_timeout_holder = setTimeout(ImageCalculationlast, 3000);
}
}
This may help you, as far as I understood. Everytime img_mouse_down() run, it will set a timeout to execute ImageCalculation(), but just before that kill any previous timeOuts, result is, if user stop clicking, ImageCalculation() will be called once 3 seconds after last click.
Something like that should address your problem. The timeout is cleared on every call and otherwise ImageCalculation is triggered after 3 seconds.
var timer = null
function img_mouse_down () {
if(leftMouseButton){
Triangulate();
if (timer !== null) {
clearTimeout(timer)
}
timer = setTimeout(function () {
ImageCalculation()
}, 3000)
}
}

Categories

Resources