[英]Delay gulp-watch execution
I am using gulp-watch
to monitor file changes and I have code that look something like this: 我正在使用
gulp-watch
监视文件更改,并且我的代码看起来像这样:
watch('public/**/*.js',function(){
runSequence('compressjs','browser-sync','jshint');
});
It works fine. 工作正常。 But because it run the task every-time as soon as there is changes to the file, it causes repeat task execution when there is more than 1 file changed.
但是,因为一旦文件发生更改,它就每次都运行任务,所以当更改了多个文件时,它将导致重复执行任务。
How can I make the delay to task execution so that when there is more than 1 file changes in a extreme short period of time, it only execute the task once and only execute after the last file changes done? 我该如何延迟执行任务,以便在极短的时间内有超过1个文件更改时,它仅执行一次任务,而仅在最后一次文件更改完成后才执行?
Taken from: https://remysharp.com/2010/07/21/throttling-function-calls#comment-216435 摘自: https : //remysharp.com/2010/07/21/throttling-function-calls#comment-216435
Try this: 尝试这个:
function debounce(fn, delay) {
var timer = null;
return function () {
var context = this, args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(context, args);
}, delay);
};
}
watch('public/**/*.js',function(){
debounce(runSequence('compressjs','browser-sync','jshint'), 500);
});
After much searching and many failures using debounce, debounce watch, I came up with a simple solution where my function 'buildAngularApp' is the equivalent of 'runSequence'. 在使用反跳,反跳监视进行了大量搜索和许多失败之后,我想出了一个简单的解决方案,其中我的函数“ buildAngularApp”等效于“ runSequence”。 Here is the code example:
这是代码示例:
//the files to watch
var backendModules = ['**/*.min.js']
var delay = 2000;
/*
The watched build task
*/
gulp.task('watchBuild', function () {
console.log('Watching: ' + backendModules);
gulp.watch(backendModules,
function () {
setTimeout(function () {
console.log('Timer ' + delay + ' Reached');
return buildAngularApp();
}, delay);
});
});
/*
The non watched task to build. calls the same build function
*/
gulp.task('build', function () {
return buildAngularApp();
})
/*
The gulp task wrapped in a function
*/
function buildAngularApp() {
return gulp.src(backendModules)
.pipe($.useref())
.pipe($.sourcemaps.init())
.pipe($.concat('app.js'))
.pipe($.sourcemaps.write('.'))
.pipe(gulp.dest('lib/js'))
.pipe($.size({
title: path.join('lib/js'),
showFiles: true
}));
}
In Gulp 4, gulp.watch
supports setting a delay. 在Gulp 4中,
gulp.watch
支持设置延迟。 See my answer here for the full low-down. 请参阅我的完整答案 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.