How can I "print" text in Javascript while pausing the script [duplicate] - javascript

This question already has answers here:
What is the JavaScript version of sleep()?
(91 answers)
Closed 9 years ago.
I have a JavaScript code that I need to add a sleep/wait function to. The code I am running is already in a function, eg:
function myFunction(time)
{
alert('time starts now');
//code to make the program wait before continuing
alert('time is up')
}
I have heard that a possible solution might include
setTimeout
but I am not sure how to use it in this case.
I can't use PHP, as my server does not support it, although using jQuery would be fine.

JS does not have a sleep function, it has setTimeout() or setInterval() functions.
If you can move the code that you need to run after the pause into the setTimeout() callback, you can do something like this:
//code before the pause
setTimeout(function(){
//do what you need here
}, 2000);
see example here : http://jsfiddle.net/9LZQp/
This won't halt the execution of your script, but due to the fact that setTimeout() is an asynchronous function, this code
console.log("HELLO");
setTimeout(function(){
console.log("THIS IS");
}, 2000);
console.log("DOG");
will print this in the console:
HELLO
DOG
THIS IS
(note that DOG is printed before THIS IS)
You can use the following code to simulate a sleep for short periods of time:
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
now, if you want to sleep for 1 second, just use:
sleep(1000);
example: http://jsfiddle.net/HrJku/1/
please note that this code will keep your script busy for n milliseconds. This will not only stop execution of Javascript on your page, but depending on the browser implementation, may possibly make the page completely unresponsive, and possibly make the entire browser unresponsive. In other words this is almost always the wrong thing to do.

Related

I need help creating a loop in dev console in firefox

I am trying to use the dev console to give mario a mushroom every 5 seconds (in the browser game super mario html5)
I can give mario mushrooms manually by typing marioShroons(mario) but I would like to have it on loop so I don't have to pause the game every time I want a mushroom. I have tried a while loop and set timeout but I can't figure it out. The only coding languages I familiar with are c++ and html.
**
while(data.time.amount > 0) {
killOtherCharacters()
}
setTimeout(function() {
killOtherCharacters()
}, 1000);
I expected these lines of code to not give me a mushroom, but to automatically kill enemies. But on the first try (the while loop) it froze the tab and I had to reload the page.
With the set timeout, it didn't make any obvious results, it killed all near characters once and then stopped.
You tried using setTimeout, and it only worked once. This is to be expected, because:
Window.setTimeout() sets a timer which executes a function or specified piece of code once the timer expires
From MDN
What you need to do is use setInterval:
The setInterval() method...repeatedly calls a function or executes a code snippet, with a fixed time delay between each call.
From MDN
So in your console, you should write this:
setInterval(killOtherCharacters, 1000);
(I removed the anonymous function because it wasn't needed - you only need an anonymous function if you're passing parameters or doing multiple things. You do need to remove the () for this though).
And if you want to stop the function from executing, assign a variable to the interval:
var killCharacters = setInterval(killOtherCharacters, 1000);
Then call clearInterval upon this variable to clear the interval (stop the loop):
clearInterval(killCharacters);
The reason your while loop froze the page is because Javascript can only do one thing at a time and you told it to always run your while function, blocking all other Javascript from running on your site.
setTimeout is only run once after a set time (see documentation), if you want to run something every x miliseconds it's better to use setInterval instead.
var intervalID = window.setInterval(killOtherCharacters(), 500); //run this every 500 ms
Use setInterval if you want killOtherCharacters() to be called repeatedly.
const interval = setInterval(function() {killOtherCharacters() },1000);
Then when you want the function to stop being called:
clearInterval(interval);

JavaScript setInterval and setTimeout timing issue [duplicate]

This question already has answers here:
Is there a more accurate way to create a Javascript timer than setTimeout?
(16 answers)
Closed 7 years ago.
Please see the following JavaScript code:
var cis_current_time = 0;
setInterval(function() {
cis_current_time += 1;
},1);
$("#timingInfo").html(cis_current_time);
setTimeout(function() {
$("#timingInfo").html($("#timingInfo").html() + ', ' + cis_current_time);
},1000);
As a result I except to get 0, 1000, but it returns 0, number near 200
Please check a fiddle.
What is the reason of such behavior?
setInterval and setTimeout may not be precise due to their design.
They are executed by the browser engine, which means the browser can throttle them in some cases. Just for an example, if your browser just uses one process for the JavaScript, they can be throttled or maybe elapse more ticks than you define, due to current pressure on your used core.
It can be improved a bit by using a multithreaded JavaScript, but anyway - they won't be 100% accurate.
setInterval only guarantees a new execution/call after the given time period. Not at the exact time. There may be differences each interval at all.
setInterval function is very precise, as you can see on this fiddle.
Problem is in your code, you are trying to execute a function each milliseconds.
setInterval(function() {
cis_current_time += 1;
},1);
JavaScript is monothreaded, then, when it has a lot of instructions, it stacks them and call them when it has the possibility, so, that's why it is not precise in your case.
setInterval is not the problem, JavaScript is : JS executes functions when it can, that's why it is executed later... Every function is concerned by this problem, so setInterval too...
Func(1) taking 70ms :
If Func(1) is taking 130ms :
setInterval is precise but has the same problem than each function in JS.
Image credits

How would I make a stopwatch in Javascript/jQuery? [duplicate]

This question already has answers here:
How to create a stopwatch using JavaScript?
(7 answers)
Closed 8 years ago.
How would I make a stopwatch in Javascript/jQuery?
I have developed a few methods of my own, here is one using while loops. This stopwatch is merely meant to count for a minute.
function myStopwatch() {
var $count = 0;
while($count < 60) {
$count++;
}
$count.delay(1000); //makes $count one second long
}
myStopwatch()
Using setInterval() may be better idea:
var count=0;
var timer = setInterval(function(){
if(count<60) count++;
else clearInterval(timer);
},3000);
Use setInterval...
var count = 0;
doEverySecond(){
// something to do every second...
count++;
if(count > 60) clearInterval(timer);
}
var timer = setInterval(doEverySecond, 1000)
jQuery's .delay() does not halt the execution of javascript like you're trying to do. It only works with asychronous operations that use the jQuery queue system such as animations which means it will do nothing in your current code since you are not using any jQuery queued operations.
In javascript, the way that you "delay" for one second is to use setTimeout() or setInterval() and specify the callback function that you want called at some future time from now.
setTimeout(function() {
// this code here will execute one second later
}, 1000);
// this code here executes immediately, there is no delay
var x = 1;
So, if you want to wait for something for a minute, you would do this:
// execute some code one minute from now
setTimeout(function() {
// this code here will execute one second later
}, 1000*60);

js setTimeout synchronize

In fact, when I use
setTimeout(a(),60);
setTimeout(a(),120);
setTimeout(a(),180);
setTimeout(a(),240);
It is supposed to be 60ms gap between calling's of a functions.
But it isnt, especially when it is fired during page loading or animating elements. In fact that gap gets even 2x longer when browser 'has hard work to do'. In some cases it can be visible easly.
The point of question is - is there any other way to synchronize events or functions in time in javascript?
The timing in setTimeout(a(),60) in simple terms translates to I will run this function no earlier than 60ms, but if I get busy it could be later than that.
Therefore, setTimeout does not promise when the execution will take place, only that it will take place sometime after the given time in milliseconds.
So to answer your question, no there is no way to guarantee execution time with setTimeout but you can load your script after the DOM has loaded so that JavaScript is not busy anymore loading other things. In jQuery you can use the $(document).ready() function for that purpose.
Read this article by John Resig for more information about timing in JavaScript: http://ejohn.org/blog/how-javascript-timers-work/
Try this:
setTimeout(a,60);
setTimeout(a,120);
setTimeout(a,180);
setTimeout(a,240);
Note that the function doesn't have the ()s.
In your particular case, setInterval() might work:
var count = 0, interval = setInterval(function() {
count += 1;
if (count > 4) {
clearInterval(interval);
} else {
a();
}
}, 60);
Note that jQuery has a built-in animation feature that uses the different, better approach of simply treating an animation as a function of time and frequently checking the clock, so an unexpected delay would simply make the animation a bit less smooth.

Pausing for a split moment in JavaScript

I have the following JavaScript code:
var cILo=true;
var img1="images/title-2a.png";
var img2="images/title-2b.png";
function loadblinker() {
for (var i=0,l=Math.floor(Math.random()*10);i<l;++i) {
cILo=!cILo;
if (cILo) {
document.getElementById("lamp").src=img1;
} else {
document.getElementById("lamp").src=img2;
}
!!!! THIS LINE HERE !!!!
}
document.getElementById("lamp").src=img1;
setTimeout("loadblinker()",Math.floor(Math.random()*10000));
}
Where I have marked the code with the phrase "!!!! THIS LINE HERE !!!!", I need some way to pause the execution for a split second. This code, when it is done, is going to give the appearance of a short circuiting light (light in the video games). I was wondering as to how I would pause the code seeing as there appears to be no natural method.
I think a better approach would be to eliminate the for loop by using setInterval. You could then clear the interval after Math.floor(Math.random()*10) iterations. I wouldn't recommend blocking execution by just spinning in a loop. Most browsers freak out when you do that.
Typically this is handled in JavaScript by calling setTimeout, passing it the code to be executed after the delay. Or in other words, instead of pausing within a function, you break your function in two: one part to be executed before the delay and the next part to be executed after.
You are already recursively calling your function via setTimeout, so you are almost there. See if you can restructure your code so that you get rid of the for loop and instead pass in the maximum number of iterations. Decrement that counter on each call. If after the decrement, your counter is greater than zero, call setTimeout to call the function again.
function pause(ms)
{
var d = new Date();
var c = null;
do
{
c= new Date();
}
while(c - d < ms);
}
Use pause(1000); to pause for 1 second.
Courtesy of this website.
Javascript in browsers does not have the ability to do a synchronous pause. You can hack your way around it, as muntoo suggested, but you shouldn't do it.

Categories