Is there a sleep function in JavaScript? [duplicate] - javascript

This question already has answers here:
What is the JavaScript version of sleep()?
(91 answers)
Closed 9 years ago.
Is there a sleep function in JavaScript?

If you are looking to block the execution of code with call to sleep, then no, there is no method for that in JavaScript.
JavaScript does have setTimeout method. setTimeout will let you defer execution of a function for x milliseconds.
setTimeout(myFunction, 3000);
// if you have defined a function named myFunction
// it will run after 3 seconds (3000 milliseconds)
Remember, this is completely different from how sleep method, if it existed, would behave.
function test1()
{
// let's say JavaScript did have a sleep function..
// sleep for 3 seconds
sleep(3000);
alert('hi');
}
If you run the above function, you will have to wait for 3 seconds (sleep method call is blocking) before you see the alert 'hi'. Unfortunately, there is no sleep function like that in JavaScript.
function test2()
{
// defer the execution of anonymous function for
// 3 seconds and go to next line of code.
setTimeout(function(){
alert('hello');
}, 3000);
alert('hi');
}
If you run test2, you will see 'hi' right away (setTimeout is non blocking) and after 3 seconds you will see the alert 'hello'.

A naive, CPU-intensive method to block execution for a number of milliseconds:
/**
* Delay for a number of milliseconds
*/
function sleep(delay) {
var start = new Date().getTime();
while (new Date().getTime() < start + delay);
}

You can use the setTimeout or setInterval functions.

function sleep(delay) {
var start = new Date().getTime();
while (new Date().getTime() < start + delay);
}
This code blocks for the specified duration. This is CPU hogging code. This is different from a thread blocking itself and releasing CPU cycles to be utilized by another thread. No such thing is going on here. Do not use this code, it's a very bad idea.

Related

How is setTimeout called in a for loop js? [duplicate]

This question already has answers here:
What is the JavaScript version of sleep()?
(91 answers)
Closed 2 years ago.
I am trying to write a for loop that has a delay between running each iteration. I thought Id go about it by using setTimeout() as follows.
Input:
for (let i=0;i<3;i++){
setTimeout(()=>{console.log("hi")},10000)
}
Output:
hi
hi
hi
What seems to be happening is that its waiting 10 seconds and then runs the entire for loop, rather than waiting 10 seconds to run each iteration of the for loop. After the first hi is shown to the console, the other 2 follow instantaneously. Why is this the case, rather than a delayed logging of hi and how can I go about doing this?
You don't call setTimeout() inside a for loop. You replace the for loop with setTimeout():
let loop = 0;
function loop () {
console.log("hi");
x++;
if (x<3) {
setTimeout(loop, 10000);
}
}
loop();
This is the traditional way of doing it. You can use a Promise with async/await in modern js to use the for loop again:
// First we need a promisified setTimeout:
function delay (ms) {
return new Promise((resolve,reject) => setTimeout(resolve,ms));
}
async function test () {
for (let i=0;i<3;i++){
await delay(10000);
console.log("hi");
}
}
test();
Javascript is asynchronous which means your timers start immediately rather than each timer blocking until done, and they all execute after roughly 10s plus a few ticks.
If you want you can try setInterval with a counter to clear it:
var counter = 0;
var interval = setInterval(function(){
console.log("hi");
counter+=1;
if (counter == 3) { clearInterval(interval); }
}, 10000);
You can probably work out an alternative using setTimeout as well.

can any one tell me what exactly setInterval() method in typescript? [duplicate]

This question already has an answer here:
setInterval and setTimeout in Typescript
(1 answer)
Closed 4 years ago.
Can any one please tell me how the setInterval() in angular is working .is java script functionality they implement in angular js ?
setInterval is a function that is exposed by the browser window as part of the global scope. Angularjs just makes use of it like any other javascript code could.
https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval
setInterval is a function that continually invokes a callback after every X milliseconds, where X is provided to setInterval.
// setInterval usage
function callback(){
console.log("callback is called continuously");
}
var repeat = 3000;
setInterval(callback, repeat);
It will continue to run as long as your program is running.
Here's another example but with canceling setInterval
var num = 0;
var intervalId = setInterval(function() {
num++;
console.log("num:", num);
if(num === 3){
clearInterval(intervlId);
}
}, 1000);
// output
num: 1
num: 2
num: 3

Run function again after x amount seconds [duplicate]

This question already has answers here:
Difference between setTimeout with and without quotes and parentheses
(7 answers)
Closed 8 years ago.
I would like to re run a the same function after x amount of seconds.
the X changes every time the function is ran like the example i have provided below but the code below does not wait half a second before fireing the function again, it just instantly runs the function in an infinite loop
test();
var interval = 500
function test() {
interval = interval + 500;
console.log("1");
setTimeout(test(), interval);
}
Change:
setTimeout(test(), interval);
to
setTimeout(test, interval);
test() calls the function immediately.

is setInterval more likely to occur on time than continuous setTimeout calls [duplicate]

This question already has answers here:
setTimeout or setInterval?
(20 answers)
Closed 8 years ago.
I have these snippets of code that do the same thing but use different approaches - setInterval and continuous setTimeout calls:
function log() {
console.log('fn')
}
//option 1
var forTimes = 10;
var doneTimes = 0;
var interval = setInterval(function(){
if (doneTimes < forTimes) {
log();
doneTimes++;
} else {
clearInterval(interval);
}
}, 100);
//option 2
function timeoutFn() {
if (doneTimes < forTimes) {
log();
doneTimes++;
setTimeout(timeoutFn, 100);
}
}
setTimeout(timeoutFn, 100);
Because of the nature of single-threaded javascript neither setTimeout nor setInterval guarantees functional call witing 100 ms since thread may be busy running an event handler or doing reflow/repaint. I'm wondering if any of them has higher likelyhood of executing handler within the specified time? If so, why? Does setInterval act like setTimeout in that it waits for the specified interval to pass and only after that adds handler to the queue?
setInterval is kind of seen as bad practice these days because you have a function being executed at intervals regardless of whether or not the previous call to the function has completed.
With regards to exact time neither is better or worse really.
The best method would be to do a recursive setTimeout Pattern:
var count = 0;
(function loopsiloop(){
setTimeout(function(){
if(count < 10) {
loopsiloop();
}
++count;
}, 100);
})();

Call a Javascript function every 5 seconds continuously [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Calling a function every 60 seconds
I want to Call a Javascript function every 5 seconds continuously.
I have seen the setTimeOut event. Will it be working fine if I want it continuously?
You can use setInterval(), the arguments are the same.
const interval = setInterval(function() {
// method to be executed;
}, 5000);
clearInterval(interval); // thanks #Luca D'Amico
Do a "recursive" setTimeout of your function, and it will keep being executed every amount of time defined:
function yourFunction(){
// do whatever you like here
setTimeout(yourFunction, 5000);
}
yourFunction();
As best coding practices suggests, use setTimeout instead of setInterval.
function foo() {
// your function code here
setTimeout(foo, 5000);
}
foo();
Please note that this is NOT a recursive function. The function is not calling itself before it ends, it's calling a setTimeout function that will be later call the same function again.
For repeating an action in the future, there is the built in setInterval function that you can use instead of setTimeout.
It has a similar signature, so the transition from one to another is simple:
setInterval(function() {
// do stuff
}, duration);
Good working example here: http://jsfiddle.net/MrTest/t4NXD/62/
Plus:
has nice fade in / fade out animation
will pause on :hover
will prevent running multiple actions (finish run animation before starting second)
will prevent going broken when in the tab ( browser stops scripts in the tabs)
Tested and working!

Categories

Resources