我試圖循環一些值,這是毫秒。我需要每隔xxxx秒運行一些代碼,具體取決於他從循環中獲得的值,但是我無法讓它正常工作,它工作正常,但不能按時運行。每個循環中的settimeout有問題
的代碼包含一個復位按鈕(代碼是從一個插件,但我不得不修改)
//插件選項
step:[
{
time: 6000,
// more stuff here
// but we dont need
// it in this example
},
{
time: 3000,
// more stuff here
// but we dont need
// it in this example
},
{
time: 12000,
// more stuff here
// but we dont need
// it in this example
}
]
//循環
var timeouts = [];
$.each(options.step, function(i, value){
var time = value.time;
timeouts.push(setTimeout(function(){
alert('some action');
},time*i));
});
//復位按鈕
$('.stop').click(function(){
$.each(timeouts, function (_, id) {
clearTimeout(id);
});
timeouts = [];
})
並不完全正確。 HTTP://計算器。com/questions/2734025/is-javascript-guaranteed-to-be-single-threaded –
@BlakeRegalia - 這篇文章與這個上下文或OP的問題無關(例如'setTimeout()'的時間)。 – jfriend00
只是說,不要在不承認角落案例的情況下就JavaScript做出大膽的一般性陳述。感謝您編輯您的答案 –