我想在javascript中创建一个延迟函数,它接受延迟时间量的参数,这样我就可以使用它在我的QML应用程序中引入JavaScript行的执行之间的延迟。它可能看起来像这样:
function delay(delayTime) {
// code to create delay
}
我需要delay()
函数的主体。请注意,JavaScript的setTimeout()
在QML中不起作用。
发布于 2019-05-07 09:40:31
下面是另一个变体,它使用Component
对象来容纳Timer
对象。
然后,我们实现一个类似setTimeout
的函数来动态创建和调用这个Timer
对象。
注:答案假设Qt5.12.x包括ECMAScript 7(因此也包括ECMAScript 6),以利用参数快捷方式、rest参数和扩展语法:
function setTimeout(func, interval, ...params) {
return setTimeoutComponent.createObject(app, { func, interval, params} );
}
function clearTimeout(timerObj) {
timerObj.stop();
timerObj.destroy();
}
Component {
id: setTimeoutComponent
Timer {
property var func
property var params
running: true
repeat: false
onTriggered: {
func(...params);
destroy();
}
}
}
在下面的代码片段中,我们将在从现在开始的0-1000ms之间的随机时间延迟内调用console.log(31)
、console.log(32)
、console.log(33)
。
console.log("Started");
setTimeout(console.log, Math.floor(1000 * Math.random()), 31);
setTimeout(console.log, Math.floor(1000 * Math.random()), 32);
setTimeout(console.log, Math.floor(1000 * Math.random()), 33);
发布于 2020-05-28 03:35:50
Bumsik Kim的答案很好,这个答案稍微改变了它,以便计时器可以重复使用,然后在需要时停止并重复使用。
要在需要的位置添加的计时器的QML。
// Allow outside access (optional)
property alias timer: timer
Timer {
id: timer
// Start the timer and execute the provided callback on every X milliseconds
function startTimer(callback, milliseconds) {
timer.interval = milliseconds;
timer.repeat = true;
timer.triggered.connect(callback);
timer.start();
}
// Stop the timer and unregister the callback
function stopTimer(callback) {
timer.stop();
timer.triggered.disconnect(callback);
}
}
这可以按如下方式使用。
timer.startTimer(Foo, 1000); // Run Foo every 1 second
timer.stopTimer(Foo); // Stop running Foo
timer.startTimer(Bar, 2000); // Run Bar every 2 seconds
timer.stopTimer(Bar); // Stop running Bar
function Foo() {
console.log('Executed Foo');
}
function Bar() {
console.log('Executed Bar');
}
发布于 2017-12-07 15:12:44
您可以使用QtTest
import QtTest 1.0
import QtQuick 2.9
ApplicationWindow{
id: window
TestEvent {
id: test
}
function delay_ms(delay_time) {
test.mouseClick(window, 0, 0, Qt.NoButton, Qt.NoModifier, delay_time)
}
}
https://stackoverflow.com/questions/28507619
复制相似问题