About JavaScript synchronization and asynchronous processing.
I'd like to put a two-second sleep process in the following source, but it doesn't work.
if(hoge){
if(!huga){
// Here's a 2-second sleep.
location.href=hoge.html;
}
if(hogeType=="a"&hugaType=="b"){
location.href=huga.html;
}
}
hogefunc(hoge, huga);
When I looked it up, I thought I could use the setTimeout
function or jQuery.Deferred
, but location.href=hoge.html;
doesn't run, but if(hogeType=="a"&hugaType=="b"){code> I'm having trouble running downstream.
How can I sleep?
JavaScript does not have a function like sleep(1000)
that stops for that line X seconds (web pages harden during script execution, so such a function is often present).
There are setTimeout
that uses the callback function instead.The function is like calling a specified function after a specified number of seconds instead of stopping.Therefore, setTimeout
runs almost instantly and beyond.
An example of a question can have the same effect as a sleep with the following:
// Everything else that might get sleep
function remaining() {
if(hoge){
if(hogeType=="a"&hugaType=="b"){
location.href=huga.html;
}
}
hogefunc(hoge, huga);
}
if(hoge&&!huga) {// Wait 2 seconds
setTimeout(function(){
location.href=hoge.html;
remaining();
}, 2000);
} else {// 2 seconds not available again
remaining();
}
I didn't know what I wanted to do, so I translated it as much as possible, but it's hard to read because there are many iterations. I think it would be a little better if I set the algorithm with callback in mind instead of sleep
.
add
Although the following code has been posted in multi-post locations, it is highly recommended that you do not use it. As mentioned above, JavaScript does not accept any user input during script execution (the browser is not weak, but HTML, CSS, and JS).It's actually like a black-and-white camera.If you don't believe it, I've prepared a code to stop for 10 seconds, so please go ahead:
//!!!!! Beware!!!!!
// The page (sometimes the entire browser) hardens for 10 seconds.
var time = new Date().getTime();
while(new Date().getTime()<time+10000);
console.log("End";
© 2024 OneMinuteCode. All rights reserved.