据我所知,这两个javascript的行为方式相同:
选项A:
function myTimeoutFunction()
{
doStuff();
setTimeout(myTimeoutFunction, 1000);
}
myTimeoutFunction();
Run Code Online (Sandbox Code Playgroud)
选项B:
function myTimeoutFunction()
{
doStuff();
}
myTimeoutFunction();
setInterval(myTimeoutFunction, 1000);
Run Code Online (Sandbox Code Playgroud)
使用setTimeout和setInterval有什么区别吗?
我想在while循环中添加延迟/睡眠:
我试过这样的:
alert('hi');
for(var start = 1; start < 10; start++) {
setTimeout(function () {
alert('hello');
}, 3000);
}
Run Code Online (Sandbox Code Playgroud)
只有第一种情况是真的:显示后alert('hi'),它将等待3秒然后alert('hello')将显示,但随后alert('hello')将反复不断.
我想要的是,在alert('hello')3秒之后显示alert('hi')之后,它需要等待第二次3秒alert('hello'),依此类推.
我有这个脚本:
for (var i = 1; i <= 2; i++) {
setTimeout(function() { alert(i) }, 100);
}
Run Code Online (Sandbox Code Playgroud)
但是3两次都被提醒,而不是1那时2.
有没有办法传递i,而不是将函数写为字符串?
所以我试图平滑地移动标记,但 id 不起作用。标记正在移动,但并不顺利,如果我写的话,我可以获得相同的结果
marker[n].setPosition(moveto);
Run Code Online (Sandbox Code Playgroud)
我已经在控制台中显示了所有变量,它很好,都以正确的方式增加,但似乎
marker[n].setPosition(latlng);
Run Code Online (Sandbox Code Playgroud)
仅在循环的最后一次迭代时调用。
这是我的代码:
function animatedMove(n, current, moveto){
var lat = current.lat();
var lng = current.lng();
var deltalat = (moveto.lat() - current.lat())/100;
var deltalng = (moveto.lng() - current.lng())/100;
for(var i=0;i<100;i++){
lat += deltalat;
lng += deltalng;
latlng = new google.maps.LatLng(lat, lng);
setTimeout(
function(){
marker[n].setPosition(latlng);
},10
);
}
}
Run Code Online (Sandbox Code Playgroud) 我希望此代码从 0 计数到 940(非常快)并在每次更新时更改文本
这是我的代码(在我的head标签内):
<script type="text/javascript">
function sleep(milliseconds) {
const date = Date.now();
let currentDate = null;
do {
currentDate = Date.now();
} while (currentDate - date < milliseconds);
}
function onLoad(){
var x = document.getElementById("numberID");
var n = 940;
var text = "";
for(i = 0;i < n + 1;i++){
text = i;
x.innerHTML = text;
sleep(1);
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
目前,它只是等待一秒钟,然后在屏幕上显示“940”并且不显示它计数。
任何帮助将不胜感激,谢谢!
这是我最近输入的代码,仍然不起作用:
const x = document.getElementById("numberID");
function newFrame(duration, start = performance.now()) {
requestAnimationFrame((now) => { …Run Code Online (Sandbox Code Playgroud)