是否有一个Javascript函数可以使代码在运行时延迟
Is there a Javascript function to make the code delay at the point that code run?
好的,我得到了这个<button onclick="alert('1');setInterval(function(){},57000);alert('2');"> Show </button>
拖延没有起作用。
setTimeout
也不起作用。
如何修复
将警报放入setInterval
回调:
<button onclick="alert('1');setInterval(function(){alert('2');},57000);"> Show </button>
代码的简单扩展版本:
var div = document.querySelector('div');
function myFunction(){
div.textContent += '-';
// beware, this code might crash your browser if left running
// for a few (thousand) years!!!
}
<button onclick="setInterval(myFunction, 1000);"> Start Interval </button>
<div></div>
上面代码的正确样式版本:
var div = document.getElementById('d');
var button = document.getElementById('b');
button.addEventListener('click', clickHandler);
function myFunction(){
div.textContent += '-';
// beware, this code might crash your browser if left running
// for a few (thousand) years!!!
}
function clickHandler(){
setInterval(myFunction, 1000);
}
<button id="b"> Start Interval </button>
<div id="d"></div>
- 工作小提琴
JavaScript代码同步运行,这意味着每条指令都是一条接一条地执行的。让我们看看你的代码:
alert('1');
setInterval(function(){
//does nothing
}, 57000);
alert('2');
现在,每一行都将一个接一个地执行,这意味着alert(1)
将执行,然后是setInterval(...)
,再是alert(2)
。您的setInterval
不会停止其他行的执行。
如果您想延迟代码执行,则必须考虑在setInterval
(我假设您想在此处使用setTimeout
)完成后执行。
此外,作为一名专业人员,您应该将JavaScript代码与HTML分离。让我们考虑以下内容:
<button id="myButton">Show</button>
...
<script>
// Get a reference to your button
var myButton = document.querySelector('#myButton');
// The code you want to execute after the given time
function executeLater(){
alert(2);
}
// We attach an event listener to your button
myButton.addEventListener('click', function(){
alert('1');
setTimeout(executeLater, 2000);
});
</script>
相关文章:
- 使用压缩的JavaScript文件(不是运行时压缩)
- 如何在运行时在angular 2中加载外部js脚本
- JavaScript错误:Microsoft JScript运行时错误:应为对象
- Google 脚本:用于创建日历活动的脚本运行时不会出错,但不会执行任何操作
- http.listen()在运行时接受终端命令
- 自定义运行时Can'在谷歌应用引擎中看不到我的自定义日志
- 实现比较方法的最佳实践是什么;s的比较类型是在运行时选择的
- JavaScript运行时是如何工作的
- 在运行时创建元素时移到一边时出错
- 如何在运行时在HTML5画布中绘制正方形
- 如何在运行时使用javascript隐藏图像
- 在webView上加载本地存储的文件时延迟
- 在运行时使用jquery准备表体会导致设计问题
- 使用主题运行时portlet liferay时出现Javascript错误
- 是否有一个Javascript函数可以使代码在运行时延迟
- 如何在另一个动画正在进行时延迟运行动画
- KO加载时运行UI延迟5秒
- 使用webkit运行iOS应用程序时延迟选择
- . slidetoggle()运行时带有延迟/抖动的动画
- 如何在第一次运行时不延迟地使用$interval