Javascript等待()函数 [英] Javascript wait() function

查看:4737
本文介绍了Javascript等待()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个javascript'等待'功能。
我应该编辑什么?

 函数wait(waitsecs){
setTimeout(donothing(),' waitsecs');


函数donothing(){

}


<解决方案

JavaScript没有线程化,所以等待会冻结整个页面(并可能导致浏览器完全停止运行脚本)。



为了特别解决您的问题,您应该在 setTimeout donothing 之后移除括号$ c>调用,并使 waitsecs 一个数字不是字符串:

 的console.log( '前'); 
setTimeout(donothing,500); // 0.5秒后运行
console.log('after');

但这不会停止执行; 之后会在您的函数运行之前被记录。



要正确地等待,您可以使用匿名函数:

 的console.log( '前'); 
setTimeout(function(){
console.log('after');
},500);

您的所有变量仍将保留在之后部分。你不应该链接这些 - 如果你发现自己需要,你需要看看你是如何构建程序。如果需要循环,也可以使用 setInterval / clearInterval


I want to create a javascript 'wait' function. what should i edit ?

function wait(waitsecs){
setTimeout(donothing(), 'waitsecs');
}

function donothing() {

}

解决方案

Javascript isn't threaded, so a "wait" would freeze the entire page (and probably cause the browser to stop running the script entirely).

To specifically address your problem, you should remove the brackets after donothing in your setTimeout call, and make waitsecs a number not a string:

console.log('before');
setTimeout(donothing,500); // run donothing after 0.5 seconds
console.log('after');

But that won't stop execution; "after" will be logged before your function runs.

To wait properly, you can use anonymous functions:

console.log('before');
setTimeout(function(){
    console.log('after');
},500);

All your variables will still be there in the "after" section. You shouldn't chain these - if you find yourself needing to, you need to look at how you're structuring the program. Also you may want to use setInterval / clearInterval if it needs to loop.

这篇关于Javascript等待()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆